ken*_*chu 20 java hadoop filewriter hdfs
我无法将数据附加到HDFS中的现有文件中.我希望如果文件存在然后附加一行,如果没有,创建一个名称给定的新文件.
这是我写入HDFS的方法.
if (!file.exists(path)){
file.createNewFile(path);
}
FSDataOutputStream fileOutputStream = file.append(path);
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
br.append("Content: " + content + "\n");
br.close();
Run Code Online (Sandbox Code Playgroud)
实际上这个方法写入HDFS并创建一个文件,但正如我所提到的那样没有追加.
这是我测试我的方法的方法:
RunTimeCalculationHdfsWrite.hdfsWriteFile("RunTimeParserLoaderMapperTest2", "Error message test 2.2", context, null);
Run Code Online (Sandbox Code Playgroud)
第一个参数是文件的名称,第二个参数是消息,另外两个参数不重要.
所以任何人都知道我错过了什么或做错了什么?
Mik*_*sov 37
实际上,您可以附加到HDFS文件:
从Client的角度来看,append操作首先调用DistributedFileSystem的append,这个操作会返回一个流对象FSDataOutputStream out.如果客户端需要将数据附加到此文件,它可以调用out.write来编写,并调用out.close来关闭.
我检查了HDFS源,有DistributedFileSystem#append方法:
FSDataOutputStream append(Path f, final int bufferSize, final Progressable progress) throws IOException
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅文稿.
您还可以通过命令行追加:
hdfs dfs -appendToFile <localsrc> ... <dst>
Run Code Online (Sandbox Code Playgroud)
直接从stdin添加行:
echo "Line-to-add" | hdfs dfs -appendToFile - <dst>
Run Code Online (Sandbox Code Playgroud)
解决了..!!
HDFS 支持追加。
你只需要做一些配置和简单的代码,如下所示:
第 1 步:在 hdfs-site.xml 中将 dfs.support.append 设置为 true:
<property>
<name>dfs.support.append</name>
<value>true</value>
</property>
Run Code Online (Sandbox Code Playgroud)
使用 stop-all.sh 停止所有守护程序服务,然后使用 start-all.sh 重新启动它
第 2 步(可选):仅当您有一个单节点集群时,您必须将复制因子设置为 1,如下所示:
通过命令行:
./hdfs dfs -setrep -R 1 filepath/directory
Run Code Online (Sandbox Code Playgroud)
或者您可以在运行时通过 java 代码执行相同的操作:
fsShell.setrepr((short) 1, filePath);
Run Code Online (Sandbox Code Playgroud)
第 3 步:用于创建/附加数据到文件中的代码:
public void createAppendHDFS() throws IOException {
Configuration hadoopConfig = new Configuration();
hadoopConfig.set("fs.defaultFS", hdfsuri);
FileSystem fileSystem = FileSystem.get(hadoopConfig);
String filePath = "/test/doc.txt";
Path hdfsPath = new Path(filePath);
fShell.setrepr((short) 1, filePath);
FSDataOutputStream fileOutputStream = null;
try {
if (fileSystem.exists(hdfsPath)) {
fileOutputStream = fileSystem.append(hdfsPath);
fileOutputStream.writeBytes("appending into file. \n");
} else {
fileOutputStream = fileSystem.create(hdfsPath);
fileOutputStream.writeBytes("creating and writing into file\n");
}
} finally {
if (fileSystem != null) {
fileSystem.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
}
}
Run Code Online (Sandbox Code Playgroud)
请让我知道任何其他帮助。
干杯。!!
HDFS不允许append操作。实现与附加相同功能的一种方法是:
| 归档时间: |
|
| 查看次数: |
37659 次 |
| 最近记录: |