HDFS API 操作之文件下载、文件删除、文件名更改

文件下载

@Test
public void testCopyToLocalFile() throws Exception {

    //1 获取文件系统
    Configuration conf = new Configuration();
    FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), conf, "root");

    //2 下载文件
    fs.copyToLocalFile(new Path("/demo/test/readme-3.md"),new Path("/Users/ylj/demo/readme-3.md"));
    //下载并删除hdfs上的文件
    fs.copyToLocalFile(true,new Path("/demo/test/readme-3.md"),new Path("/Users/ylj/demo/readme-3.md"));
    //下载并删除hdfs上的文件,不开启文件校验。
    fs.copyToLocalFile(true,new Path("/demo/test/readme-3.md"),new Path("/Users/ylj/demo/readme-3.md"),false);

    //3 关闭资源
    fs.close();

    System.out.println("~ok~");

}

文件删除

@Test
public void testDelete() throws Exception {

    //1 获取文件系统
    Configuration conf = new Configuration();
    FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), conf, "root");

    //2 删除文件或文件夹,是否递归
    fs.delete(new Path("/demo/test/readme.md"),true);

    //3 关闭资源
    fs.close();

    System.out.println("~ok~");

}

文件名更改

@Test
public void testRename() throws Exception {

    //1 获取文件系统
    Configuration conf = new Configuration();
    FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), conf, "root");

    //2 文件名、文件夹名更改
    fs.rename(new Path("/demo/test/readme.md"),new Path("/demo/test/readme_bak.md"));

    //3 关闭资源
    fs.close();

    System.out.println("~ok~");

}

猜你喜欢

转载自blog.csdn.net/yljphp/article/details/88960348