HDFS文件内容追加(Append)
HDFS设计之处并不支持给文件追加内容,这样的设计是有其背景的(如果想了解更多关于HDFS的append的曲折实现,可以参考《File Appends in HDFS》:http://blog.cloudera.com/blog/2009/07/file-appends-in-hdfs/),但从HDFS2.x开始支持给文件追加内容,可以参见https://issues.apache.org/jira/browse/HADOOP-8230。可以再看看http://www.quora.com/HDFS/Is-HDFS-an-append-only-file-system-Then-how-do-people-modify-the-files-stored-on-HDFS。正如HADOOP-8230所述,只需要将hdfs-site.xml中的以下属性修改为true就行。
目前如何在命令行里面给HDFS文件中追加内容我还没找到相应的方法。但是,我们可以通过Hadoop提供的API实现文件内容追加,如何实现?这里我写了一个简单的测试程序:
将上面的代码打包成jar(这里我取名为hdfs.jar)文件,然后上传到机器中,比如我上传到我的home目录,在程序运行前,我们来看看HDFS中wyp.txt文件中的内容有什么
好,我们再来看看/home/wyp/append.txt文件中的内容:
看完代码中所涉及到的两个文件之后,我们再运行hdfs.jar
运行完之后,看看wyp.txt内容
好了,wyp.txt文件已经追加了append.txt文件中的内容了。
原文出自:http://www.iteblog.com/archives/881
========================================================================
hadoop 测试例子:
========================================================================
public static void main(String[] args) {
// TODO Auto-generated method stub
String newFilePath = args[0];
String totalFilePath = args[1];
System.out.println("new file path:"+newFilePath);
System.out.println("total file path:"+totalFilePath);
Configuration conf = new Configuration();
conf.setBoolean("dfs.support.append", true);
FileSystem fs_new = null;
FileSystem fs_total = null;
InputStream in = null;
OutputStream out = null;
try {
fs_new = FileSystem.get(URI.create(newFilePath), conf);
fs_total = FileSystem.get(URI.create(totalFilePath), conf);
in = new BufferedInputStream(fs_new.open(new Path(newFilePath)));
out = fs_total.append(new Path(totalFilePath));
IOUtils.copyBytes(in, out, conf, true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}