java实现对hdfs上文件的上传与下载

从hdfs上下载到本地

/**
*src:hdfs路径  例:hdfs://192.168.0.168:9000/data/a.json
*dst:本地路径
*/   

 public static void Hdfs2Local(String src, String dst) {

        try {
            Configuration conf = new Configuration();
            FileSystem fs = FileSystem.get(URI.create(src), conf);

            Path srcPath = new Path(src);
            Path dstPath = new Path(dst);
            fs.copyToLocalFile(srcPath, dstPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

从本地上传到hdfs

/**
 *@Author huangzx
 *@Description:
 *@Date 2:58 PM 2/21/19
 *@Param src:本地文件路径
 *@Param dst:hdfs路径
 *@return void
 */
    public static void Local2Hdfs(String src, String dst) {

        try {
            Configuration conf = new Configuration();
            FileSystem fs = FileSystem.get(URI.create(dst), conf);

            Path srcPath = new Path(src);
            Path dstPath = new Path(dst);

            fs.copyFromLocalFile(true, true, srcPath, dstPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

这里有几个地方需要注意一下,以前hdfs端口默认是9000,新版变成8020了,具体从哪个版本开始我也忘了,具体查看配置文件core-sile.xml里的配置

如果程序出现拒绝连接的情况请查看coresite.xml文件的


    fs.defaultFS
    hdfs://node01:9000

在单机版的时候记住千万不可把node01改成localhost或者127.0.0.1,在/etc/hosts里面配置一组ip与本机主机名的映射,将node01改成你主机的ip或者是主机名,并重启hdfs即可

你可能感兴趣的:(大数据,java)