//读取配置文件
Configuration conf = new Configuration();
//获取文件系统
FileSystem fs = FileSystem.get(conf);
1. 创建文件夹
Path srcPath = new Path(path);
//调用mkdir()创建目录,(可以一次性创建,以及不存在的父目录)
boolean flag = fs.mkdirs(srcPath);
2. 创建文件并写入数据
Path dstPath = new Path(dst);
//打开一个输出流
FSDataOutputStream outputStream = fs.create(dstPath);
outputStream.write(contents);
3. 追加写
InputStream in = new BufferedInputStream(new FileInputStream(src));
//文件输出流写入
FSDataOutputStream out = fs.append(dstPath);
IOUtils.copyBytes(in, out, 4096,true);
4. 列出目录下所有文件
FileStatus[] listStatus = fs.listStatus(new Path("/"));
for(FileStatus f:listStatus){
String type="-";
if(f.isDirectory()) type=“d”;
System.out.println(type+"\t"+f.getPath().getName());
}
fs.close();
5. 修改目录及文件权限
6. 查看目录及文件权限
7. 删除文件/目录
Path path = new Path(filePath);
//调用deleteOnExit()
boolean flag = fs.deleteOnExit(path);
8. 上传本地文件
Path srcPath = new Path(src); //原路径
Path dstPath = new Path(dst); //目标路径
//调用文件系统的文件复制函数,前面参数是指是否删除原文件,true为删除,默认为false
fs.copyFromLocalFile(false,srcPath, dstPath);
9. 下载文件到本地
fs.copyToLocalFile(false, new Path("/jdk-7u65-linux-i586.tar.gz"), new Path(“C:/”), true);
fs.close();
10. 文件重命名
Path oldPath = new Path(oldName);
Path newPath = new Path(newName);
boolean flag = fs.rename(oldPath, newPath);
11. 判断目录/文件是否存在
boolean exist=fs.exists(path)
12. 文件输入流
InputStream in = null;
try {
in = fs.open(new Path(uri));
//复制到标准输出流
IOUtils.copyBytes(in, System.out, 4096,false);
} catch (Exception e) {
e.printStackTrace();
}finally{
IOUtils.closeStream(in);
}
13. 修改文件副本数量
fs.setReplication(new Path("/jdk-7u65-linux-i586.tgz"), (short)2);
14. 获取文件block信息
RemoteIterator listFiles = fs.listFiles(new Path("/"), true);
while(listFiles.hasNext()){
LocatedFileStatus fileStatus = listFiles.next();
System.out.println(fileStatus.getPath().getName());
}
15. 获取block位置信息
16. 获取block偏移量信息
BlockLocation[] fileBlockLocations = fs.getFileBlockLocations(new Path("/jdk-7u65-linux-i586.tar.gz"), 0, 143588167);
for(BlockLocation location : fileBlockLocations){
System.out.println(location.getOffset());
System.out.println(location.getNames()[0]);
}
17. 从指定偏移量读取数据
FSDataInputStream in = fs.open(new Path("/test.txt"));
in.seek(6);//定位,设置起始偏移量
FileOutputStream out=new FileOutputStream(“c:/test.seg.txt”);
IOUtils.copyBytes(in, out, new Configuration());
IOUtils.closeStream(in);
IOUtils.closeStream(out);
fs.close();
18. 判断是否为目录
fs.isDirectory(path)