将数据附加到HDFS Java中的现有文件
我无法将数据附加到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();
实际上这个方法写入HDFS并创建一个文件,但正如我所提到的那样没有追加。
这是我测试我的方法的方法:
RunTimeCalculationHdfsWrite.hdfsWriteFile("RunTimeParserLoaderMapperTest2", "Error message test 2.2", context, null);
第一个参数是文件的名称,第二个参数是消息,另外两个参数不重要。
所以任何人都知道我错过了什么或做错了什么?
实际上,您可以附加到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
有关详情,请参阅演示文稿
您也可以通过命令行追加:
hdfs dfs -appendToFile ...
直接从stdin添加行:
echo "Line-to-add" | hdfs dfs -appendToFile -
HDFS不允许append
操作。 实现与追加相同function的一种方法是:
- 检查文件是否存在。
- 如果文件不存在,则创建新文件并写入新文件
- 如果文件存在,则创建一个临时文件。
- 从原始文件读取行并将该行写入临时文件(不要忘记换行)
- 写下要附加到临时文件的行。
- 最后,删除原始文件并将临时文件移动(重命名)为原始文件。
解决了..!!
HDFS支持追加。
您只需要执行一些配置和简单的代码,如下所示:
步骤1 :在hdfs-site.xml中将dfs.support.append设置为true:
dfs.support.append true
使用stop-all.sh停止所有守护程序服务,然后使用start-all.sh重新启动它
步骤2(可选) :仅当您具有单节点群集时,必须将复制因子设置为1,如下所示:
通过命令行:
./hdfs dfs -setrep -R 1 filepath/directory
或者您可以在运行时通过Java代码执行相同的操作:
fShell.setrepr((short) 1, filePath);
第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(); } } }
如有任何其他帮助,请告诉我。
干杯。!!