【HDFS API编程】查看HDFS文件内容、创建文件并写入内容、更改文件名

首先,重点重复重复再重复:

/**
 * 使用Java API操作HDFS文件系统
 * 关键点:
 * 1)创建 Configuration
 * 2)获取 FileSystem
 * 3)...剩下的就是 HDFS API的操作了
*/

回顾:https://www.cnblogs.com/Liuyt-61/p/10737466.html

先上代码(注意包不要导错了):

public class HDFSApp {
public static final String HDFS_PATH = "hdfs://hadoop000:8020"; FileSystem fileSystem = null; Configuration configuration = null; @Before public void setUp() throws Exception{ System.out.println("setUp-----------"); configuration = new Configuration();/* * 构造一个访问制定HDFS系统的客户端对象 * 第一个参数:HDFS的URI * 第二个参数:客户端制定的配置参数 * 第三个参数:客户端的身份,说白了就是用户名 */ fileSystem = FileSystem.get(new URI(HDFS_PATH),configuration,"hadoop"); } /* * 查看HDFS内容 */ @Test public void text() throws Exception{ FSDataInputStream in = fileSystem.open(new Path("/README.txt")); IOUtils.copyBytes(in,System.out,1024); } /* * 创建文件 */ @Test public void create() throws Exception{ FSDataOutputStream out = fileSystem.create(new Path("/hdfsapi/test/a.txt")); out.writeUTF("Hello hadoop"); out.flush();//输出走缓冲区,所以先flush out.close(); } @After public void tearDown(){ configuration = null; fileSystem = null; System.out.println("----------tearDown------"); } }

首先可以先通过hadoop命令将本地的随便的一个txt文件传入文件系统 / 目录下来做测试,例如README.txt

hadoop fs -put /home/hadoop/README.txt /

我们使用ls查看下是否上传成功,ls查看已经显示存在我们刚刚上传的 README.txt文件,我们进行下一步操作

[hadoop@hadoop000 ~]$ hadoop fs -ls /

Found 2 items
-rw-r--r--   1 hadoop supergroup       1366 2019-04-19 16:19 /README.txt
drwxr-xr-x   - hadoop supergroup          0 2019-04-19 16:11 /hdfsapi

查看HDFS文件内容:使用fileSystem的open方法打开文件,方法怎么用?Ctrl点进去源码:

/**
* Opens an FSDataInputStream at the indicated Path.
* @param f the file to open
* 功能:在指定路径打开fsdatainputstream。
* @参数 f 要打开的文件
*/ 
  public FSDataInputStream open(Path f) throws IOException {
    return open(f, getConf().getInt("io.file.buffer.size", 4096));
  }

告诉我们方法功能是在指定路径打开FSDataInputStream

参数f是要打开的文件的Path,返回值是FSDataInputStream,这是什么?看名字这是一个文件系统数据的输入流,同样可以Ctrl点进去看源码的注释介绍。

然后我们需要使用一个IOUtils类来将fsdatainputstream流中的数据打印输出。IOUtils是什么呢?同样哪里不会Ctrl点哪里!

源码中类的介绍是:An utility class for I/O related functionality.( I/O相关功能的实用程序类。)

使用IOUtils的copyBytes方法将fsdatainputstream流中的数据打印输出到控制台显示。Ctrl点进去看这个方法怎么用:

/**
   * Copies from one stream to another.
   * 
   * @param in InputStrem to read from
   * @param out OutputStream to write to
   * @param buffSize the size of the buffer 
   */
  public static void copyBytes(InputStream in, OutputStream out, int buffSize) 
    throws IOException {
    PrintStream ps = out instanceof PrintStream ? (PrintStream)out : null;
    byte buf[] = new byte[buffSize];
    int bytesRead = in.read(buf);
    while (bytesRead >= 0) {
      out.write(buf, 0, bytesRead);
      if ((ps != null) && ps.checkError()) {
        throw new IOException("Unable to write to output stream.");
      }
      bytesRead = in.read(buf);
    }
  }

看代码注释地方介绍了该方法的功能是从一个流复制到另一个流,介绍了各个参数,所以我们能够写出代码:


FSDataInputStream in = fileSystem.open(new Path("/README.txt"));
IOUtils.copyBytes(in,System.out,1024);

我们运行测试类text()即可在IDEA控制台看到输出README.txt的内容。

既然能够读取文件内容那自然可以创建文件并写入内容。

使用fileSystem的create()方法进行创建fsdataoutpustream(正好与上面的fsdatainputstream对应):
 /**
   * Create an FSDataOutputStream at the indicated Path.
   * Files are overwritten by default.
   * @param f the file to create
   * 在指定路径创建fsdataoutputstream。
   * 默认情况下会覆盖文件。
   * @参数 f 要创建的文件  
*/
  public FSDataOutputStream create(Path f) throws IOException {
    return create(f, true);
  }

使用out的write方法进行写操作,例如使用writeUTF():

out.writeUTF("Hello hadoop");
out.flush();//输出走缓冲区,所以先flush
out.close();//关闭fsdataoutputstream

out的写还有很多方法,每个方法都可以Ctrl点进去看方法的介绍。

运行create测试方法之后,我们可以回到终端控制台使用先使用hadoop的-ls命令查看文件是否创建成功,再使用-text命令查看是否写入内容成功。

[hadoop@hadoop000 ~]$ hadoop fs -ls /hdfsapi/test
Found 1 items
-rw-r--r--   3 hadoop supergroup         14 2019-04-19 16:31 /hdfsapi/test/a.txt

[hadoop@hadoop000 ~]$ hadoop fs -text /hdfsapi/test/a.txt Hello hadoop[hadoop@hadoop000 ~]$

创建文件并写入内容成功。

接着看更改文件名操作:

首先我们-ls查看到当前/hdfsapi/test目录下有a.txt和b.txt两个文件

[hadoop@hadoop000 sbin]$ hadoop fs -ls /hdfsapi/test
Found 2 items
-rw-r--r--   3 hadoop supergroup         14 2019-04-19 16:31 /hdfsapi/test/a.txt
-rw-r--r--   1 hadoop supergroup         28 2019-04-19 16:50 /hdfsapi/test/b.txt

我们使用fileSystem的rename方法,操作将b.txt重命名为c.txt

rename方法怎么使用?哪里不会Ctrl点哪里。点进去看到方法的源码介绍我们得知方法的功能是Renames Path src to Path dst(将路径SRC重命名为路径DST),两个参数是旧的Path和新的Path,返回值是布尔类型。

所以我们可以写:

    /*
     * 测试文件名更改
     */
    @Test
    public void rename() throws Exception{
        Path oldPath = new Path("/hdfsapi/test/b.txt");
        Path newPath = new Path("/hdfsapi/test/c.txt");
        Boolean result = fileSystem.rename(oldPath,newPath);
        System.out.println(result);
    }

运行之后打印出true,返回终端-ls查看,重命名成功。

[hadoop@hadoop000 sbin]$ hadoop fs -ls /hdfsapi/test
Found 2 items
-rw-r--r--   3 hadoop supergroup         14 2019-04-19 16:31 /hdfsapi/test/a.txt
-rw-r--r--   1 hadoop supergroup         28 2019-04-19 16:50 /hdfsapi/test/c.txt
原文地址:https://www.cnblogs.com/Liuyt-61/p/10739018.html