【发布时间】:2014-03-06 12:06:51
【问题描述】:
我想存储当前正在运行的查询的详细信息,例如执行查询的文件名和时间。为此,我在 HDFS 中创建了一个文件,试图写入信息。但问题是如何将数据附加到现有文件中。请帮我。提前致谢
【问题讨论】:
我想存储当前正在运行的查询的详细信息,例如执行查询的文件名和时间。为此,我在 HDFS 中创建了一个文件,试图写入信息。但问题是如何将数据附加到现有文件中。请帮我。提前致谢
【问题讨论】:
首先停止所有 Hadoop 守护进程并在 hdfs-site.xml 中添加以下属性:
<property>
<name>dfs.support.append</name>
<value>true</value>
</property>
现在,重新启动守护程序并尝试以下代码:
public class HDFSAppend {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Configuration conf = new Configuration();
conf.addResource(new Path("/path/to/your/hadoop/directory/conf/core-site.xml"));
conf.addResource(new Path("/path/to/your/hadoop/directory/conf/hdfs-site.xml"));
FileSystem fs = FileSystem.get(conf);
FSDataOutputStream out = fs.append(new Path("/demo.txt"));
out.writeUTF("Append demo...");
fs.close();
}
}
HTH
【讨论】:
您可以从命令行执行此操作:
$ hadoop fs -appendToFile <local_file> <hdfs_file>
如果您使用的是 java,请参阅此问题: Write a file in hdfs with Java
【讨论】:
从命令行执行此操作的最简单方法是:
echo -e 'Hello\nWorld' | hadoop dfs -put - /1.txt
这将在HDFS的路径/中创建一个文件1.txt,并将在其中存储两行Hello\nWorld。
【讨论】:
使用命令: hdfs dfs -put file_location hdfs_location
注意:hdfs_location 已启用
【讨论】:
解决了..!!
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();
}
}
}
如果有任何其他帮助,请告诉我。
干杯。!!
【讨论】: