JAVA操作HDFS案例的简单实现
Jar包引入,pom.xml:
- <dependency>
- <groupId>org.apache.hadoop</groupId>
- <artifactId>hadoop-common</artifactId>
- <version>2.8.0</version>
- </dependency>
- <dependency>
- <groupId>org.apache.hadoop</groupId>
- <artifactId>hadoop-hdfs</artifactId>
- <version>2.8.0</version>
- </dependency>
将本地文件上传到hdfs服务器:
- /**
- * 上传文件到hdfs上
- */
- @Test
- public void upload() throws IOException {
- Configuration conf = new Configuration();
- conf.set("fs.defaultFS","hdfs://hzq:9000");
- FileSystem fs = FileSystem.get(conf);
- fs.copyFromLocalFile(new Path("/home/hzq/jdk1.8.tar.gz"),new Path("/demo"));
- }
在开发中我没有引入“core-site.xml”配置文件,所以在本地调用时使用conf进行配置“conf.set("fs.defaultFS","hdfs://hzq:9000");“,下面雷同。
将hdfs上文件下载到本地:
- /**
- * 将hdfs上文件下载到本地
- */
- @Test
- public void download() throws IOException {
- Configuration conf = new Configuration();
- conf.set("fs.defaultFS","hdfs://hzq:9000");
- FileSystem fs = FileSystem.newInstance(conf);
- fs.copyToLocalFile(new Path("/java/jdk1.8.tar.gz"),new Path("/home/hzq/"));
- }
- /**
- * 删除hdfs上的文件
- * @throws IOException
- */
- @Test
- public void removeFile() throws IOException {
- Configuration conf = new Configuration();
- conf.set("fs.defaultFS","hdfs://hzq:9000");
- FileSystem fs = FileSystem.newInstance(conf);
- fs.delete(new Path("/demo/jdk1.8.tar.gz"),true);
- }
- /**
- * 在hdfs更目录下面创建test1文件夹
- * @throws IOException
- */
- @Test
- public void mkdir() throws IOException {
- Configuration conf = new Configuration();
- conf.set("fs.defaultFS","hdfs://hzq:9000");
- FileSystem fs = FileSystem.newInstance(conf);
- fs.mkdirs(new Path("/test1"));
- }
- @Test
- public void listFiles() throws IOException {
- Configuration conf = new Configuration();
- conf.set("fs.defaultFS","hdfs://hzq:9000");
- FileSystem fs = FileSystem.newInstance(conf);
- // true 表示递归查找 false 不进行递归查找
- RemoteIterator<LocatedFileStatus> iterator = fs.listFiles(new Path("/"), true);
- while (iterator.hasNext()){
- LocatedFileStatus next = iterator.next();
- System.out.println(next.getPath());
- }
- System.out.println("----------------------------------------------------------");
- FileStatus[] fileStatuses = fs.listStatus(new Path("/"));
- for (int i = 0; i < fileStatuses.length; i++) {
- FileStatus fileStatus = fileStatuses[i];
- System.out.println(fileStatus.getPath());
- }
- }
结果分析:
“listFiles“列出的是hdfs上所有文件的路径,不包括文件夹。根据你的设置,支持递归查找。
”listStatus“列出的是所有的文件和文件夹,不支持递归查找。如许递归,需要自己实现。