Java 读写 hdfs文件或者目录

1.读取单个文件

[java] view plain copy

  1. Date date = DateUtil.getSpecifiedDayBefore();  
  2. String yesterday = DateUtil.dateToStr(date, "yyyy-MM-dd");  
  3. String path = "hdfs://ip:9000/output_log/output_log_click" + yesterday;  
  4.   
  5.  Configuration conf = new Configuration();  
  6. FileSystem fs = FileSystem.get(URI.create(path), conf);  
  7. FSDataInputStream hdfsInStream = fs.open(new Path(path));  
  8. InputStreamReader isr = new InputStreamReader(hdfsInStream, "utf-8");  
  9. BufferedReader br = new BufferedReader(isr);  
  10. String line;  
  11. // int k = 0;  
  12. while ((line = br.readLine()) != null) {  
  13.     System.out.println(line);  
  14. }  
  15.    


 

2.读取文件夹

[java] view plain copy

  1. Date date = DateUtil.getSpecifiedDayBefore();  
  2. String yesterday = DateUtil.dateToStr(date, "yyyy-MM-dd");  
  3. String path = "hdfs://ip:9000/output_log/output_log_click" + yesterday;  
  4.   
  5. Configuration conf = new Configuration();  
  6. FileSystem fs = FileSystem.get(URI.create(path), conf);  
  7. FileStatus[] status = fs.listStatus(new Path(path));  
  8. for (FileStatus file : status) {  
  9.     if (!file.getPath().getName().startsWith("newsMap")) {  
  10.               continue;  
  11.           }  
  12.     FSDataInputStream hdfsInStream = fs.open(file.getPath());  
  13.     InputStreamReader isr = new InputStreamReader(hdfsInStream, "utf-8");  
  14.     BufferedReader br = new BufferedReader(isr);  
  15.     String line;  
  16.     // int k = 0;  
  17.     while ((line = br.readLine()) != null) {  
  18.         System.out.println(line);  
  19.     }  
  20.       
  21. }  

猜你喜欢

转载自blog.csdn.net/hellozhxy/article/details/84337651