当前位置:   article > 正文

使用Java API对HDFS进行如下操作:文件的创建、上传、下载以及删除等操作_第2关:hdfs java api编程——文件上传

第2关:hdfs java api编程——文件上传
  1. HDFS-JAVA接口:上传文件

将一个本地文件(无具体要求)上传至HDFS中的/hdfs-test路径下(如无此路径,新建一个)。

新建路径:

 首先在路径/usr/test/ 下新建test.txt,指令为:/usr/test/test.txt,然后进行上传操作。

  1. package org.apache.hadoop.examples;
  2. import java.io.FileInputStream;
  3. public class module_info {
  4. public static void main(String[] args) throws Exception {
  5. Configuration conf=new Configuration();
  6. URI uri=new URI("hdfs://192.168.46.xxx:9000");
  7. FileSystem fs=FileSystem.get(uri,conf,"hadoop");
  8. Path src=new Path("/usr/test/test.txt");
  9. Path dst=new Path("/hdfs-test/test.txt");
  10. fs.copyFromLocalFile(src, dst);
  11. fs.close();
  12. System.out.println("Upload Successfully!");
  13. // TODO Auto-generated method stub
  14. }
  15. }

     2.HDFS-JAVA接口:创建文件

在HDFS中的/hdfs-test路径下新建一个data.txt文件。

  1. package org.apache.hadoop.examples1;
  2. import java.io.FileInputStream;
  3. public class CreateText {
  4. public static void main(String[] args) throws Exception{
  5. // TODO Auto-generated method stub
  6. Configuration conf = new Configuration();
  7. URI uri = new URI("hdfs://192.168.46.xxx:9000");
  8. FileSystem fs = FileSystem.get(uri, conf, "hadoop");
  9. Path path = new Path("/hdfs-test/data.txt");
  10. FSDataOutputStream newFile = fs.create(path, true);
  11. newFile.writeBytes("hello");
  12. newFile.close();
  13. fs.close();
  14. }
  15. }

查询发现/hdfs-test路径下新建了一个data.txt文件

输入指令查看文件内容

    3.HDFS-JAVA接口:下载文件

将HDFS中的/hdfs-test/data.txt文件下载到本地任一路径下。

  1. package org.apache.hadoop.examples;
  2. import java.net.URI;
  3. public class DownloadText {
  4. public static void main(String[] args) throws Exception {
  5. Configuration conf=new Configuration();
  6. URI uri=new URI("hdfs://192.168.46.xxx:9000");
  7. FileSystem fs=FileSystem.get(uri,conf,"hadoop");
  8. Path src=new Path("/hdfs-test/data.txt");
  9. Path dst=new Path("/usr/test/data.txt");
  10. fs.copyToLocalFile(false,src,dst,true);
  11. fs.close();
  12. System.out.println("Download Successfully!");
  13. // TODO Auto-generated method stub
  14. }
  15. }

根据路径/usr/test/data.txt查看内容,发现下载的文件data.txt

   4.HDFS-JAVA接口:删除文件

将HDFS中/hdfs-test路径下的data.txt删除。

  1. package org.apache.hadoop.examples;
  2. import java.net.URI;
  3. public class DeleteTxt {
  4. public static void main(String[] args) throws Exception {
  5. Configuration conf=new Configuration();
  6. URI uri=new URI("hdfs://192.168.46.xxx:9000");
  7. FileSystem fs=FileSystem.get(uri,conf,"hadoop");
  8. Path path=new Path("/hdfs-test/data.txt");
  9. fs.delete(path);
  10. fs.close();
  11. System.out.println("Delete File Successdully!");
  12. // TODO Auto-generated method stub
  13. }
  14. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/721842
推荐阅读
相关标签
  

闽ICP备14008679号