将数据附加到HDFS Java中的现有文件

时间:2014-04-10 19:20:45

标签: java hadoop hdfs filewriter

我无法将数据附加到HDFS中的现有文件中。我希望如果文件存在则添加一行,如果没有,则创建一个名为given的新文件。

这是我写入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);

第一个参数是文件的名称,第二个参数是消息,另外两个参数不重要。

所以任何人都知道我错过了什么或做错了什么?

3 个答案:

答案 0 :(得分:36)

实际上,您可以附加到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

有关详细信息,请参阅presentation

您也可以通过命令行追加:

hdfs dfs -appendToFile <localsrc> ... <dst>

直接从stdin中添加行:

echo "Line-to-add" | hdfs dfs -appendToFile - <dst>

答案 1 :(得分:3)

HDFS不允许append次操作。实现与追加相同功能的一种方法是:

  • 检查文件是否存在。
  • 如果文件不存在,则创建新文件&amp;写入新文件
  • 如果文件存在,请创建一个临时文件。
  • 从原始文件读取行&amp;将同一行写入临时文件(不要忘记换行符)
  • 将要附加的行写入临时文件。
  • 最后,删除原始文件&amp;将临时文件移动(重命名)为原始文件。

答案 2 :(得分:3)

<强>解决.. !!

HDFS支持追加。

您只需执行一些配置和简单代码,如下所示:

第1步:在hdfs-site.xml中将dfs.support.append设置为true:

<property>
   <name>dfs.support.append</name>
   <value>true</value>
</property>

使用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();
        }
    }
}

请让我知道任何其他帮助。

干杯!!

相关问题