首页 > 解决方案 > 如何以编程方式在 hdfs 中创建/触摸文件?

问题描述

有没有办法用Java在hdfs中创建触摸文件?

类似于FileUtils类在 apache commons 中提供的内容。

如果我们touch的文件已经存在,它会将上次修改时间更新为当前时间。如果该文件不存在,它将创建一个空白文件,并将当前时间作为最后修改时间。

标签: javahadoophdfs

解决方案


java hadoop FileSystem api 提供了这些类型的助手。

touch这是为 hdfs复制经典的一种方法:

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.FSDataOutputStream;
import java.io.IOException;

public static void touch(String filePath) throws IOException {

  FileSystem hdfs = FileSystem.get(new Configuration());

  Path fileToTouch = new Path(filePath);

  FSDataOutputStream fos = null;

  // If the file already exists, we append an empty String just to modify
  // the timestamp:
  if (hdfs.exists(fileToTouch)) {
    fos = hdfs.append(new Path(filePath));
    fos.writeBytes("");
  }
  // Otherwise, we create an empty file:
  else {
    fos = hdfs.create(new Path(filePath));
  }

  fos.close();
}

如果文件不存在,这将创建一个空文件:

hdfs.create(new Path(filePath)).close();

如果文件已经存在,则将一个空字符串附加到文件中,以修改时间戳:

hdfs.append(new Path(filePath)).writeBytes("");

推荐阅读