2014年10月10日 11:58:29 阅读数:7940
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就行。
2
<name>dfs.support.append</name>
目前如何在命令行里面给HDFS文件中追加内容我还没找到相应的方法。但是,我们可以通过Hadoop 提供的API实现文件内容追加,如何实现?这里我写了一个简单的测试程序:
03
import
org.apache.hadoop.conf.Configuration;
04
import
org.apache.hadoop.fs.FileSystem;
05
import
org.apache.hadoop.fs.Path;
06
import
org.apache.hadoop.io.IOUtils;
16
public
class
AppendContent {
17
public
static
void
main(String[] args) {
19
Configuration conf =
new
Configuration();
20
conf.setBoolean(
"dfs.support.append"
,
true
);
22
String inpath =
"/home/wyp/append.txt"
;
25
fs = FileSystem.get(URI.create(hdfs_path), conf);
28
BufferedInputStream(
new
FileInputStream(inpath));
29
OutputStream out = fs.append(
new
Path(hdfs_path));
30
IOUtils.copyBytes(in, out,
4096
,
true
);
31
}
catch
(IOException e) {
将上面的代码打包成jar(这里我取名为hdfs.jar)文件,然后上传到机器中,比如我上传到我的home目录,在程序运行前,我们来看看HDFS中wyp.txt文件中的内容有什么
1
[wyp
@l
-datalogm1.data.cn1 ~]$ /home/q/hadoop-
2.2
.
0
/bin/hadoop fs \
4
[wyp
@l
-datalogm1.data.cn1 ~]$
好,我们再来看看/home/wyp/append.txt文件中的内容:
1
[wyp
@l
-datalogm1.data.cn1 ~]$ vim append.txt
看完代码中所涉及到的两个文件之后,我们再运行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 \
好了,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(); } }
=======================================================================