1

Is there any way to create touch a file in hdfs with Java?

Similar to what the FileUtils class provides in apache commons.

If we touch a file that already exists, it would update the last modified time to the current time. And if the file doesn't exist, it would create a blank file with the current time as last modified time.

Xavier Guihot
  • 54,987
  • 21
  • 291
  • 190
Shats107
  • 13
  • 1
  • 5

1 Answers1

1

The java hadoop FileSystem api provides these types of helpers.

Here is a way to replicate a classic touch for 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();
}

This creates an empty file if the file doesn't already exist:

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

And appends an empty String to the file if it already exist, in order to modify the timestamp:

hdfs.append(new Path(filePath)).writeBytes("");
Xavier Guihot
  • 54,987
  • 21
  • 291
  • 190