- 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就行。
- <property>
- <name>dfs.support.append</name>
- <value>true</value>
- </property>
- package com.wyp;
- import org.apache.hadoop.conf.Configuration;
- import org.apache.hadoop.fs.FileSystem;
- import org.apache.hadoop.fs.Path;
- import org.apache.hadoop.io.IOUtils;
- import java.io.*;
- import java.net.URI;
- /**
- * blog: http://www.iteblog.com/
- * Date: 14-1-2
- * Time: 下午6:09
- */
- public class AppendContent {
- public static void main(String[] args) {
- String hdfs_path = "hdfs://mycluster/home/wyp/wyp.txt";//文件路径
- Configuration conf = new Configuration();
- conf.setBoolean("dfs.support.append", true);
- String inpath = "/home/wyp/append.txt";
- FileSystem fs = null;
- try {
- fs = FileSystem.get(URI.create(hdfs_path), conf);
- //要追加的文件流,inpath为文件
- InputStream in = new
- BufferedInputStream(new FileInputStream(inpath));
- OutputStream out = fs.append(new Path(hdfs_path));
- IOUtils.copyBytes(in, out, 4096, true);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
将上面的代码打包成jar(这里我取名为hdfs.jar)文件,然后上传到机器中,比如我上传到我的home目录,在程序运行前,我们来看看HDFS中wyp.txt文件中的内容有什么
1 | [wyp @l -datalogm1.data.cn1 ~]$ /home/q/hadoop- 2.2 . 0 /bin/hadoop fs \ |
2 | -cat /home/wyp/wyp.txt |
3 | 123456 |
4 | [wyp @l -datalogm1.data.cn1 ~]$ |
好,我们再来看看/home/wyp/append.txt文件中的内容:
1 | [wyp @l -datalogm1.data.cn1 ~]$ vim append.txt |
2 | wyp append test |
看完代码中所涉及到的两个文件之后,我们再运行hdfs.jar
1 | [wyp @l -datalogm1.data.cn1 ~]$ /home/q/hadoop- 2.2 . 0 /bin/hadoop jar \ |
2 | hdfs.jar com.wyp.AppendContent |
运行完之后,看看wyp.txt内容
1 | [wyp @l -datalogm1.data.cn1 ~]$ /home/q/hadoop- 2.2 . 0 /bin/hadoop fs \ |
2 | -cat /home/wyp/wyp.txt |
3 | 123456 |
4 | wyp append test |
好了,wyp.txt文件已经追加了append.txt文件中的内容了。