java - 如何以编程方式在 hdfs 中创建/触摸文件?
问题描述
有没有办法用Java在hdfs中创建触摸文件?
类似于FileUtils
类在 apache commons 中提供的内容。
如果我们touch
的文件已经存在,它会将上次修改时间更新为当前时间。如果该文件不存在,它将创建一个空白文件,并将当前时间作为最后修改时间。
解决方案
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("");
推荐阅读
- powershell - 为什么 write-host 输出到成绩单但 write-information 没有?
- stripe-payments - 前端 <-> 后端:安全条带集成
- javascript - React native `input` 必须是一个未定义的函数
- amazon-s3 - 构建数据迁移和加载默认数据流程的建议
- r - 在 R 中,在展平嵌套列表时生成正确的列名
- git - ssh 代理 plink 无法弹出 yubikey 输入表单
- reactjs - React Hook Form:当我渲染一个 TextField (materialUI) 并提供 Field: {onChange} 它说 onChange undefined
- sql - 2个表中的SQL多对多关系
- r - 按 DF 中的某个变量分组
- swift - 使用 AVFoundation 快速多摄像头预览