Linux学习篇3-关于HDFS的Java的API写法关键代码

//读取配置文件
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)

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值