ToB企服应用市场:ToB评测及商务社交产业平台

标题: 大数据编程实验二:认识常用的HDFS操纵 [打印本页]

作者: 商道如狼道    时间: 2024-10-11 19:54
标题: 大数据编程实验二:认识常用的HDFS操纵
实验目的
1、明白HDFS在Hadoop体系结构中的角色
2、认识利用HDFS操纵常用的Shell命令
3、认识HDFS操纵常用的Java API
实验平台
1、操纵体系:Windows
2、Hadoop版本:3.1.3
3、JDK版本:1.8
4、Java IDE:IDEA

实验步调

前期:一定要先启动hadoop
  1. cd /usr/local/hadoop
  2. ./sbin/start-dfs.sh
复制代码

 1、编程实现以下功能,并利用Hadoop提供的Shell命令完成雷同任务
1)向 HDFS 中上传恣意文本文件,如果指定的文件在 HDFS 中已经存在,则由用户来指定是追加到原有文件末端还是覆盖原有的文件;
Shell 命令
检查文件是否存在,可以利用如下命令:
  1. cd /usr/local/hadoop
  2. ./bin/hdfs dfs -test -e text.txt
复制代码

 实行完上述命令不会输出效果,需要继承输入命令检察效果:
  1. echo $?
复制代码

 如果效果显示文件已经存在,则用户可以选择追加到原来文件末端或者覆盖原来文件,
具体命令如下:
  1. cd /usr/local/hadoop
  2. ./bin/hdfs dfs -appendToFile local.txt text.txt #追加到原文件末尾
  3. ./bin/hdfs dfs -copyFromLocal -f local.txt text.txt #覆盖原来文件,第一种命令形式
  4. ./bin/hdfs dfs -cp -f file:///home/hadoop/local.txt text.txt#覆盖原来文件,第二种命令形式
复制代码

 现实上,也可以不用上述方法,而是接纳如下命令来实现:(注意要加上./bin/)
  1. if $(./bin/hdfs dfs -test -e text.txt);
  2. then $(./bin/hdfs dfs -appendToFile local.txt text.txt);
  3. else $(./bin/hdfs dfs -copyFromLocal -f local.txt text.txt);
  4. fi
复制代码
上述代码可视为一行代码,在终端中输入第一行代码后,代码不会立即被实行,可以继承输入第 2 行代码和第 3 行代码,直到输入 fi 以后,上述代码才会真正实行。另外,上述代码中,直接利用了 hdfs 命令,而没有给出命令的路径,因为,这里假设已经配置了 PATH环境变量,把 hdfs 命令的路径“/usr/local/hadoop/bin”写入了 PATH 环境变量中。
接纳idea来进行java代码编写
前期:先导JAR包

点击Project Structure......
 

 选择Libraries,以及中央的 +

 选择Java,开始跟据下方图片进行4个导包

(1)/usr/local/hadoop/share/hadoop/common
 

shift + ↓ 可以选中多个。
(2)/usr/local/hadoop/share/hadoop/common/lib



 lib下全部的JVR包

 (3)/usr/local/hadoop/share/hadoop/hdfs

 

 (4)/usr/local/hadoop/share/hadoop/hdfs/lib

lib下面的全部JVR包
 


 最终导入后: 
 

选择Apply,再OK


 项目结构目录:

 HDFSApi.java
  1. package HDFSApi;
  2. import org.apache.hadoop.conf.Configuration;
  3. import org.apache.hadoop.fs.*;
  4. import java.io.*;
  5. public class HDFSApi {
  6.     /**
  7.      * 判断路径是否存在
  8.      */
  9.     public static boolean test(Configuration conf, String path) throws IOException {
  10.         FileSystem fs = FileSystem.get(conf);
  11.         return fs.exists(new Path(path));
  12.     }
  13.     /**
  14.      * 复制文件到指定路径
  15.      * 若路径已存在,则进行覆盖
  16.      */
  17.     public static void copyFromLocalFile(Configuration conf, String localFilePath, String
  18.             remoteFilePath) throws IOException {
  19.         FileSystem fs = FileSystem.get(conf);
  20.         Path localPath = new Path(localFilePath);
  21.         Path remotePath = new Path(remoteFilePath);
  22. /* fs.copyFromLocalFile 第一个参数表示是否删除源文件,第二个参数表示是否覆
  23. 盖 */
  24.         fs.copyFromLocalFile(false, true, localPath, remotePath);
  25.         fs.close();
  26.     }
  27.     /**
  28.      * 追加文件内容
  29.      */
  30.     public static void appendToFile(Configuration conf, String localFilePath, String
  31.             remoteFilePath) throws IOException {
  32.         FileSystem fs = FileSystem.get(conf);
  33.         Path remotePath = new Path(remoteFilePath);
  34.         /* 创建一个文件读入流 */
  35.         FileInputStream in = new FileInputStream(localFilePath);
  36.         /* 创建一个文件输出流,输出的内容将追加到文件末尾 */
  37.         FSDataOutputStream out = fs.append(remotePath);
  38.         /* 读写文件内容 */
  39.         byte[] data = new byte[1024];
  40.         int read = -1;
  41.         while ( (read = in.read(data)) > 0 ) {
  42.             out.write(data, 0, read);
  43.         }
  44.         out.close();
  45.         in.close();
  46.         fs.close();
  47.     }
  48.     /**
  49.      * 主函数
  50.      */
  51.     public static void main(String[] args) {
  52.         Configuration conf = new Configuration();
  53.         conf.set("fs.default.name","hdfs://localhost:9000");
  54.         String localFilePath = "/home/hadoop/text.txt"; // 本地路径
  55.         String remoteFilePath = "/user/hadoop/text.txt"; // HDFS 路径
  56.         String choice = "append"; // 若文件存在则追加到文件末尾
  57. // String choice = "overwrite"; // 若文件存在则覆盖
  58.         try {
  59.             /* 判断文件是否存在 */
  60.             Boolean fileExists = false;
  61.             if (HDFSApi.test(conf, remoteFilePath)) {
  62.                 fileExists = true;
  63.                 System.out.println(remoteFilePath + " 已存在.");
  64.             } else {
  65.                 System.out.println(remoteFilePath + " 不存在.");
  66.             }
  67.             /* 进行处理 */
  68.             if ( !fileExists) { // 文件不存在,则上传
  69.                 HDFSApi.copyFromLocalFile(conf, localFilePath, remoteFilePath);
  70.                 System.out.println(localFilePath + " 已上传至 " + remoteFilePath);
  71.             } else if ( choice.equals("overwrite") ) { // 选择覆盖
  72.                 HDFSApi.copyFromLocalFile(conf, localFilePath, remoteFilePath);
  73.                 System.out.println(localFilePath + " 已覆盖 " + remoteFilePath);
  74.             } else if ( choice.equals("append") ) { // 选择追加
  75.                 HDFSApi.appendToFile(conf, localFilePath, remoteFilePath);
  76.                 System.out.println(localFilePath + " 已追加至 " + remoteFilePath);
  77.             }
  78.         } catch (Exception e) {
  79.             e.printStackTrace();
  80.         }
  81.     }
  82. }
复制代码
log4j.properties
  1. log4j.rootLogger=info,consolePrint,errorFile,logFile
  2. log4j.appender.consolePrint.Encoding = UTF-8
  3. log4j.appender.consolePrint = org.apache.log4j.ConsoleAppender
  4. log4j.appender.consolePrint.Target = System.out
  5. log4j.appender.consolePrint.layout = org.apache.log4j.PatternLayout
  6. log4j.appender.consolePrint.layout.ConversionPattern=%d %p [%c] - %m%n
  7. log4j.appender.logFile.Encoding = UTF-8
  8. log4j.appender.logFile = org.apache.log4j.DailyRollingFileAppender
  9. log4j.appender.logFile.File = D:/eclipse/log4j_properties_runlog/WorldCount_demo_run.log
  10. log4j.appender.logFile.Append = true
  11. log4j.appender.logFile.Threshold = info
  12. log4j.appender.logFile.layout = org.apache.log4j.PatternLayout
  13. log4j.appender.logFile.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n
  14. log4j.appender.errorFile.Encoding = UTF-8
  15. log4j.appender.errorFile = org.apache.log4j.DailyRollingFileAppender
  16. log4j.appender.errorFile.File = D:/eclipse/log4j_properties_runlog/WorldCount_demo_error.log
  17. log4j.appender.errorFile.Append = true
  18. log4j.appender.errorFile.Threshold = ERROR
  19. log4j.appender.errorFile.layout = org.apache.log4j.PatternLayout
  20. log4j.appender.errorFile.layout.ConversionPattern =%-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n
复制代码
然后运行,
(可能出错)

 办理方法,弄一个text.txt文件,应该是在前面没有弄成功

 运行成功


   (2) 从   HDFS   中下载指定文件,如果当地文件与要下载的文件名称雷同,则自动对下     载的文件重定名;   
  1. if $(./bin/hdfs dfs -test -e file:///home/hadoop/text.txt);
  2. then $(./bin/hdfs dfs -copyToLocal text.txt ./text2.txt);
  3. else $(./bin/hdfs dfs -copyToLocal text.txt ./text.txt);
  4. fi
复制代码

   Java代码(记得新建项目、再重新导包)
  shiyan2.2
  

  1. package HDFSApi;
  2. import org.apache.hadoop.conf.Configuration;
  3. import org.apache.hadoop.fs.*;
  4. import java.io.*;
  5. public class HDFSApi {
  6.     /**
  7.      * 下载文件到本地
  8.      * 判断本地路径是否已存在,若已存在,则自动进行重命名
  9.      */
  10.     public static void copyToLocal(Configuration conf, String remoteFilePath, String
  11.             localFilePath) throws IOException {
  12.         FileSystem fs = FileSystem.get(conf);
  13.         Path remotePath = new Path(remoteFilePath);
  14.         File f = new File(localFilePath);
  15.         /* 如果文件名存在,自动重命名(在文件名后面加上 _0, _1 ...) */
  16.         if (f.exists()) {
  17.             System.out.println(localFilePath + " 已存在.");
  18.             Integer i = 0;
  19.             while (true) {
  20.                 f = new File(localFilePath + "_" + i.toString());
  21.                 if (!f.exists()) {
  22.                     localFilePath = localFilePath + "_" + i.toString();
  23.                     break;
  24.                 }
  25.             }
  26.             System.out.println("将重新命名为: " + localFilePath);
  27.         }
  28.         // 下载文件到本地
  29.         Path localPath = new Path(localFilePath);
  30.         fs.copyToLocalFile(remotePath, localPath);
  31.         fs.close();
  32.     }
  33.     /**
  34.      * 主函数
  35.      */
  36.     public static void main(String[] args) {
  37.         Configuration conf = new Configuration();
  38.         conf.set("fs.default.name","hdfs://localhost:9000");
  39.         String localFilePath = "/home/hadoop/text.txt"; // 本地路径
  40.         String remoteFilePath = "/user/hadoop/text.txt"; // HDFS 路径
  41.         try {
  42.             HDFSApi.copyToLocal(conf, remoteFilePath, localFilePath);
  43.             System.out.println("下载完成");
  44.         } catch (Exception e) {
  45.             e.printStackTrace();
  46.         }
  47.     }
  48. }
复制代码

  记得把之前的 log4j.properties弄进项目里(在上方有)
   

   运行成功
  

  
   (3) 将 HDFS 中指定文件的内容输出到终端中
shell命令
  1. ./bin/hdfs dfs -cat text.txt
复制代码

  shiyan2.3
  

    java命令
  1. package HDFSApi;
  2. import org.apache.hadoop.conf.Configuration;
  3. import org.apache.hadoop.fs.*;
  4. import java.io.*;
  5. public class HDFSApi {
  6.     /**
  7.      * 读取文件内容
  8.      */
  9.     public static void cat(Configuration conf, String remoteFilePath) throws IOException {
  10.         FileSystem fs = FileSystem.get(conf);
  11.         Path remotePath = new Path(remoteFilePath);
  12.         FSDataInputStream in = fs.open(remotePath);
  13.         BufferedReader d = new BufferedReader(new InputStreamReader(in));
  14.         String line = null;
  15.         while ( (line = d.readLine()) != null ) {
  16.             System.out.println(line);
  17.         }
  18.         d.close();
  19.         in.close();
  20.         fs.close();
  21.     }
  22.     /**
  23.      * 主函数
  24.      */
  25.     public static void main(String[] args) {
  26.         Configuration conf = new Configuration();
  27.         conf.set("fs.default.name","hdfs://localhost:9000");
  28.         String remoteFilePath = "/user/hadoop/text.txt"; // HDFS 路径
  29.         try {
  30.             System.out.println("读取文件: " + remoteFilePath);
  31.             HDFSApi.cat(conf, remoteFilePath);
  32.             System.out.println("\n 读取完成");
  33.         } catch (Exception e) {
  34.             e.printStackTrace();
  35.         }
  36.     }
  37. }
复制代码

   (4) 显示 HDFS 中指定的文件的读写权限、巨细、创建时间、路径等信息;
shell命令
  1. ./bin/hdfs dfs -ls -h text.txt
复制代码

  
  
  
  
  (5) 给定 HDFS 中某一个目录,输出该目录下的全部文件的读写权限、巨细、创建时
间、路径等信息,如果该文件是目录,则递归输出该目录下全部文件相关信息;

shell命令
  1. cd /usr/local/hadoop
  2. ./bin/hdfs dfs -ls -R -h /user/hadoop
复制代码

  
(6) 提供一个 HDFS 内的文件的路径,对该文件进行创建和删除操纵。如果文件所在
目录不存在,则自动创建目录;
shell命令
  1. if $(./bin/hdfs dfs -test -d dir1/dir2);
  2. then $(./bin/hdfs dfs -touchz dir1/dir2/filename);
  3. else $(./bin/hdfs dfs -mkdir -p dir1/dir2 && ./bin/hdfs dfs -touchz dir1/dir2/filename);
  4. fi
  5. ./bin/hdfs dfs -rm dir1/dir2/filename #删除文件
复制代码

 shiyan2.6

 Java代码
  1. package HDFSApi;
  2. import org.apache.hadoop.conf.Configuration;
  3. import org.apache.hadoop.fs.*;
  4. import java.io.*;
  5. public class HDFSApi {
  6.     /**
  7.      * 判断路径是否存在
  8.      */
  9.     public static boolean test(Configuration conf, String path) throws IOException {
  10.         FileSystem fs = FileSystem.get(conf);
  11.         return fs.exists(new Path(path));
  12.     }
  13.     /**
  14.      * 创建目录
  15.      */
  16.     public static boolean mkdir(Configuration conf, String remoteDir) throws IOException {
  17.         FileSystem fs = FileSystem.get(conf);
  18.         Path dirPath = new Path(remoteDir);
  19.         boolean result = fs.mkdirs(dirPath);
  20.         fs.close();
  21.         return result;
  22.     }
  23.     /**
  24.      * 创建文件
  25.      */
  26.     public static void touchz(Configuration conf, String remoteFilePath) throws IOException {
  27.         FileSystem fs = FileSystem.get(conf);
  28.         Path remotePath = new Path(remoteFilePath);
  29.         FSDataOutputStream outputStream = fs.create(remotePath);
  30.         outputStream.close();
  31.         fs.close();
  32.     }
  33.     /**
  34.      * 删除文件
  35.      */
  36.     public static boolean rm(Configuration conf, String remoteFilePath) throws IOException {
  37.         FileSystem fs = FileSystem.get(conf);
  38.         Path remotePath = new Path(remoteFilePath);
  39.         boolean result = fs.delete(remotePath, false);
  40.         fs.close();
  41.         return result;
  42.     }
  43.     /**
  44.      * 主函数
  45.      */
  46.     public static void main(String[] args) {
  47.         Configuration conf = new Configuration();
  48.         conf.set("fs.default.name","hdfs://localhost:9000");
  49.         String remoteFilePath = "/user/hadoop/input/text.txt"; // HDFS 路径
  50.         String remoteDir = "/user/hadoop/input"; // HDFS 路径对应的目录
  51.         try {
  52.             /* 判断路径是否存在,存在则删除,否则进行创建 */
  53.             if ( HDFSApi.test(conf, remoteFilePath) ) {
  54.                 HDFSApi.rm(conf, remoteFilePath); // 删除
  55.                 System.out.println("删除路径: " + remoteFilePath);
  56.             } else {
  57.                 if ( !HDFSApi.test(conf, remoteDir) ) { // 若目录不存在,则进行创建
  58.                     HDFSApi.mkdir(conf, remoteDir);
  59.                     System.out.println("创建文件夹: " + remoteDir);
  60.                 }
  61.                 HDFSApi.touchz(conf, remoteFilePath);
  62.                 System.out.println("创建路径: " + remoteFilePath);
  63.             }
  64.         } catch (Exception e) {
  65.             e.printStackTrace();
  66.         }
  67.     }
  68. }
复制代码



 (7) 提供一个 HDFS 的目录的路径,对该目录进行创建和删除操纵。创建目录时,如
果目录文件所在目录不存在,则自动创建相应目录;删除目录时,由用户指定
当该目录不为空时是否还删除该目录;

shell命令
创建目录的命令如下:
  1. ./bin/hdfs dfs -mkdir -p dir1/dir2
复制代码
删除目录的命令如下:
  1. ./bin/hdfs dfs -rmdir dir1/dir2
复制代码
上述命令实行以后,如果目录非空,则会提示 not empty,删除操纵不会实行。如果要
逼迫删除目录,可以利用如下命令:
  1. ./bin/hdfs dfs -rm -R dir1/dir2
复制代码


 shiyan2.7

java代码

  1. package HDFSApi;
  2. import org.apache.hadoop.conf.Configuration;
  3. import org.apache.hadoop.fs.*;
  4. import java.io.*;
  5. public class HDFSApi {
  6.     /**
  7.      * 判断路径是否存在
  8.      */
  9.     public static boolean test(Configuration conf, String path) throws IOException {
  10.         FileSystem fs = FileSystem.get(conf);
  11.         return fs.exists(new Path(path));
  12.     }
  13.     /**
  14.      * 判断目录是否为空
  15.      * true: 空,false: 非空
  16.      */
  17.     public static boolean isDirEmpty(Configuration conf, String remoteDir) throws IOException {
  18.         FileSystem fs = FileSystem.get(conf);
  19.         Path dirPath = new Path(remoteDir);
  20.         RemoteIterator<LocatedFileStatus> remoteIterator = fs.listFiles(dirPath, true);
  21.         return !remoteIterator.hasNext();
  22.     }
  23.     /**
  24.      * 创建目录
  25.      */
  26.     public static boolean mkdir(Configuration conf, String remoteDir) throws IOException {
  27.         FileSystem fs = FileSystem.get(conf);
  28.         Path dirPath = new Path(remoteDir);
  29.         boolean result = fs.mkdirs(dirPath);
  30.         fs.close();
  31.         return result;
  32.     }
  33.     /**
  34.      * 删除目录
  35.      */
  36.     public static boolean rmDir(Configuration conf, String remoteDir) throws IOException {
  37.         FileSystem fs = FileSystem.get(conf);
  38.         Path dirPath = new Path(remoteDir);
  39.         /* 第二个参数表示是否递归删除所有文件 */
  40.         boolean result = fs.delete(dirPath, true);
  41.         fs.close();
  42.         return result;
  43.     }
  44.     /**
  45.      * 主函数
  46.      */
  47.     public static void main(String[] args) {
  48.         Configuration conf = new Configuration();
  49.         conf.set("fs.default.name","hdfs://localhost:9000");
  50.         String remoteDir = "/user/hadoop/input"; // HDFS 目录
  51.         Boolean forceDelete = false; // 是否强制删除
  52.         try {
  53.             /* 判断目录是否存在,不存在则创建,存在则删除 */
  54.             if ( !HDFSApi.test(conf, remoteDir) ) {
  55.                 HDFSApi.mkdir(conf, remoteDir); // 创建目录
  56.                 System.out.println("创建目录: " + remoteDir);
  57.             } else {
  58.                 if ( HDFSApi.isDirEmpty(conf, remoteDir) || forceDelete ) { // 目录为空或强制删除
  59.                     HDFSApi.rmDir(conf, remoteDir);
  60.                     System.out.println("删除目录: " + remoteDir);
  61.                 } else { // 目录不为空
  62.                     System.out.println("目录不为空,不删除: " + remoteDir);
  63.                 }
  64.             }
  65.         } catch (Exception e) {
  66.             e.printStackTrace();
  67.         }
  68.     }
  69. }
复制代码

 8) 向HDFS中指定的文件追加内容,由用户指定内容追加到原有文件的开头或结尾;
shell命令
追加到原文件末端的命令如下

  1. ./bin/hdfs dfs -appendToFile local.txt text.txt
复制代码

追加到原文件的开头,在 HDFS 中不存在与这种操纵对应的命令,因此,无法利用一条
命令来完成。可以先移动到当地进行操纵,再进行上传覆盖,具体命令如下: 
无此文件,则新建此文件

 


  1. ./bin/hdfs dfs -get text.txt
  2. cat text.txt >> local.txt
  3. ./bin/hdfs dfs -copyFromLocal -f local.txt text.txt
复制代码
 

 继承·
  1. ./bin/hdfs dfs -appendToFile local.txt text.txt
复制代码
 


 shiyan2.8

 java代码
  1. package HDFSApi;
  2. import org.apache.hadoop.conf.Configuration;
  3. import org.apache.hadoop.fs.*;
  4. import java.io.*;
  5. public class HDFSApi {
  6.     /**
  7.      * 判断路径是否存在
  8.      */
  9.     public static boolean test(Configuration conf, String path) throws IOException {
  10.         FileSystem fs = FileSystem.get(conf);
  11.         return fs.exists(new Path(path));
  12.     }
  13.     /**
  14.      * 追加文本内容
  15.      */
  16.     public static void appendContentToFile(Configuration conf, String content, String
  17.             remoteFilePath) throws IOException {
  18.         FileSystem fs = FileSystem.get(conf);
  19.         Path remotePath = new Path(remoteFilePath);
  20.         /* 创建一个文件输出流,输出的内容将追加到文件末尾 */
  21.         FSDataOutputStream out = fs.append(remotePath);
  22.         out.write(content.getBytes());
  23.         out.close();
  24.         fs.close();
  25.     }
  26.     /**
  27.      * 追加文件内容
  28.      */
  29.     public static void appendToFile(Configuration conf, String localFilePath, String
  30.             remoteFilePath) throws IOException {
  31.         FileSystem fs = FileSystem.get(conf);
  32.         Path remotePath = new Path(remoteFilePath);
  33.         /* 创建一个文件读入流 */
  34.         FileInputStream in = new FileInputStream(localFilePath);
  35.         /* 创建一个文件输出流,输出的内容将追加到文件末尾 */
  36.         FSDataOutputStream out = fs.append(remotePath);
  37.         /* 读写文件内容 */
  38.         byte[] data = new byte[1024];
  39.         int read = -1;
  40.         while ( (read = in.read(data)) > 0 ) {
  41.             out.write(data, 0, read);
  42.         }
  43.         out.close();
  44.         in.close();
  45.         fs.close();
  46.     }
  47.     /**
  48.      * 移动文件到本地
  49.      * 移动后,删除源文件
  50.      */
  51.     public static void moveToLocalFile(Configuration conf, String remoteFilePath, String
  52.             localFilePath) throws IOException {
  53.         FileSystem fs = FileSystem.get(conf);
  54.         Path remotePath = new Path(remoteFilePath);
  55.         Path localPath = new Path(localFilePath);
  56.         fs.moveToLocalFile(remotePath, localPath);
  57.     }
  58.     /**
  59.      * 创建文件
  60.      */
  61.     public static void touchz(Configuration conf, String remoteFilePath) throws IOException {
  62.         FileSystem fs = FileSystem.get(conf);
  63.         Path remotePath = new Path(remoteFilePath);
  64.         FSDataOutputStream outputStream = fs.create(remotePath);
  65.         outputStream.close();
  66.         fs.close();
  67.     }
  68.     /**
  69.      * 主函数
  70.      */
  71.     public static void main(String[] args) {
  72.         Configuration conf = new Configuration();
  73.         conf.set("fs.default.name","hdfs://localhost:9000");
  74.         String remoteFilePath = "/user/hadoop/text.txt"; // HDFS 文件
  75.         String content = "新追加的内容\n";
  76.         String choice = "after"; //追加到文件末尾
  77. // String choice = "before"; // 追加到文件开头
  78.         try {
  79.             /* 判断文件是否存在 */
  80.             if ( !HDFSApi.test(conf, remoteFilePath) ) {
  81.                 System.out.println("文件不存在: " + remoteFilePath);
  82.             } else {
  83.                 if ( choice.equals("after") ) { // 追加在文件末尾
  84.                     HDFSApi.appendContentToFile(conf, content, remoteFilePath);
  85.                     System.out.println("已追加内容到文件末尾" + remoteFilePath);
  86.                 } else if ( choice.equals("before") ) { // 追加到文件开头
  87.                     /* 没有相应的 api 可以直接操作,因此先把文件移动到本地*/
  88.                     /*创建一个新的 HDFS,再按顺序追加内容 */
  89.                     String localTmpPath = "/user/hadoop/tmp.txt";
  90. // 移动到本地
  91.                     HDFSApi.moveToLocalFile(conf, remoteFilePath, localTmpPath);
  92.                     // 创建一个新文件
  93.                     HDFSApi.touchz(conf, remoteFilePath);
  94.                     // 先写入新内容
  95.                     HDFSApi.appendContentToFile(conf, content, remoteFilePath);
  96.                     // 再写入原来内容
  97.                     HDFSApi.appendToFile(conf, localTmpPath, remoteFilePath);
  98.                     System.out.println("已追加内容到文件开头: " + remoteFilePath);
  99.                 }
  100.             }
  101.         } catch (Exception e) {
  102.             e.printStackTrace();
  103.         }
  104.     }
  105. }
复制代码
 


 (9) 删除 HDFS 中指定的文件
shell命令
  1. ./bin/hdfs dfs -rm text.txt
复制代码
 



  1. package HDFSApi;
  2. import org.apache.hadoop.conf.Configuration;
  3. import org.apache.hadoop.fs.*;
  4. import java.io.*;
  5. public class HDFSApi {
  6.     /**
  7.      * 删除文件
  8.      */
  9.     public static boolean rm(Configuration conf, String remoteFilePath) throws IOException {
  10.         FileSystem fs = FileSystem.get(conf);
  11.         Path remotePath = new Path(remoteFilePath);
  12.         boolean result = fs.delete(remotePath, false);
  13.         fs.close();
  14.         return result;
  15.     }
  16.     /**
  17.      * 主函数
  18.      */
  19.     public static void main(String[] args) {
  20.         Configuration conf = new Configuration();
  21.         conf.set("fs.default.name","hdfs://localhost:9000");
  22.         String remoteFilePath = "/user/hadoop/text.txt"; // HDFS 文件
  23.         try {
  24.             if ( HDFSApi.rm(conf, remoteFilePath) ) {
  25.                 System.out.println("文件删除: " + remoteFilePath);
  26.             } else {
  27.                 System.out.println("操作失败(文件不存在或删除失败)");
  28.             }
  29.         } catch (Exception e) {
  30.             e.printStackTrace();
  31.         }
  32.     }
  33. }
复制代码

 (10) 在 HDFS 中,将文件从源路径移动到目的路径
shell命令
  1. ./bin/hdfs dfs -mv text.txt text2.txt
复制代码

 

  1. package HDFSApi;
  2. import org.apache.hadoop.conf.Configuration;
  3. import org.apache.hadoop.fs.*;
  4. import java.io.*;
  5. public class HDFSApi {
  6.     /**
  7.      * 移动文件
  8.      */
  9.     public static boolean mv(Configuration conf, String remoteFilePath, String
  10.             remoteToFilePath) throws IOException {
  11.         FileSystem fs = FileSystem.get(conf);
  12.         Path srcPath = new Path(remoteFilePath);
  13.         Path dstPath = new Path(remoteToFilePath);
  14.         boolean result = fs.rename(srcPath, dstPath);
  15.         fs.close();
  16.         return result;
  17.     }
  18.     /**
  19.      * 主函数
  20.      */
  21.     public static void main(String[] args) {
  22.         Configuration conf = new Configuration();
  23.         conf.set("fs.default.name","hdfs://localhost:9000");
  24.         String remoteFilePath = "hdfs:///user/hadoop/text.txt"; // 源文件 HDFS 路径
  25.         String remoteToFilePath = "hdfs:///user/hadoop/new.txt"; // 目的 HDFS 路径
  26.         try {
  27.             if ( HDFSApi.mv(conf, remoteFilePath, remoteToFilePath) ) {
  28.                 System.out.println(" 将文件 " + remoteFilePath + " 移动到 " +
  29.                         remoteToFilePath);
  30.             } else {
  31.                 System.out.println("操作失败(源文件不存在或移动失败)");
  32.             }
  33.         } catch (Exception e) {
  34.             e.printStackTrace();
  35.         }
  36.     }
  37. }
复制代码

 (二)编程实现一个类“MyFSDataInputStream”
该类继承“org.apache.hadoop.fs.FSDataInputStream”,要求如下:实现按行读取 HDFS 中指定文件的方法“readLine()”,如果读到文件末端,则返回空,否则返回文件一行的文本。

在终端中先进入hadoop中,然后输入命令bin/hadoop dfsadmin -safemode leave使其离开安全模式
运行过程如图:



免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4