我们向/maven下上传一个文件。 要用到的api是put (或者copyFormLocalFile)。核心代码如下。
public void testCopyFromLocalFile() throws IOException, InterruptedException, URISyntaxException {// 1 获取文件系统Configuration configuration = new Configuration();FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:8020"), configuration, "root");// 2 上传文件fs.copyFromLocalFile(new Path("d:/sunwukong.txt"), new Path("/maven"));// 3 关闭资源fs.close();
}
上传结束之后,回到hdfs的UI界面去检查是否成功。
动态设置副本份数(参数优先级)
默认情况下,上传的文件会被保存3份,如果需要的话,我们可以随时去修改这个设置参数。
参数优先级排序:(1)客户端代码中设置的值 >(2)然后是服务器的自定义配置(xxx-site.xml) >(3)服务器的默认配置(xxx-default.xml)
参考代码如下:
@Test
public void testCopyFromLocalFile() throws IOException, InterruptedException, URISyntaxException {// 1 获取文件系统Configuration configuration = new Configuration();configuration.set("dfs.replication", "2");FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:8020"), configuration, "root");// 2 上传文件fs.copyFromLocalFile(new Path("d:/sunwukong.txt"), new Path("/xiyou/huaguoshan"));// 3 关闭资源fs.close();
}
修改这个值之后,我们再去重新上传一个新的文件,并检查是否在hdfs的UI面板中能看到这个数值的变化。
HDFS文件下载
接下来,我们看如何去下载文件。这个过程需要调用copyToLocalFile这个API。具体的测试代码如下:
@Test
public void testCopyToLocalFile() throws IOException, InterruptedException, URISyntaxException{// 1 获取文件系统Configuration configuration = new Configuration();FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:8020"), configuration, "root");// 2 执行下载操作// boolean delSrc 指是否将原文件删除// Path src 指要下载的文件路径// Path dst 指将文件下载到的路径// boolean useRawLocalFileSystem 是否开启文件校验fs.copyToLocalFile(false, new Path("/xiyou/huaguoshan/sunwukong.txt"), new Path("d:/sunwukong2.txt"), true);// 3 关闭资源fs.close();
}
注意:如果执行上面代码,下载不了文件,有可能是你电脑的微软支持的运行库少,需要安装一下微软运行库。