hdfs copyToLocalFile拷贝文件到本地

有时候需要将集群上的文件拷贝到执行机工作目录里,常使用copyToLocalFile函数
代码如下:

public static void getFileFromHDFS(String hdfssrc, String localdst) {
    Log.info("copy file from hdfs to local...");
    Configuration conf = new Configuration();
    Path src = new Path(hdfssrc);
    Path dst = new Path(localdst);
    try {
      FileSystem fs = src.getFileSystem(conf);
      fs.copyToLocalFile(false, src, dst, true);
      fs.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

FileSystem的获取很关键,如果使用 FileSystem fs= FileSystem.get(conf); 获取fs会出现类似如下错误
Error: java.lang.IllegalArgumentException: Wrong FS: hdfs://expected: viewfs://nsX/
大多数网上说的做法是把集群上的core-site.xml和hdfs-site.xml放到当前工程下,但这不是正规处理。正确做法是使用srcPath生成FileSystem

猜你喜欢

转载自blog.csdn.net/banana1006034246/article/details/84109049