使用Java在hdfs中写入文件

我想在HDFS中创建文件并在其中写入数据。我使用以下代码:


Configuration config = new Configuration();     

FileSystem fs = FileSystem.get(config); 

Path filenamePath = new Path("input.txt");  

try {

    if (fs.exists(filenamePath)) {

        fs.delete(filenamePath, true);

    }


    FSDataOutputStream fin = fs.create(filenamePath);

    fin.writeUTF("hello");

    fin.close();

}

它创建文件,但不写任何东西。我搜索了很多,但没有找到任何东西。我怎么了 我是否需要任何许可才能在HDFS中写入?


谢谢。


慕的地6264312
浏览 2786回答 3
3回答

30秒到达战场

HADOOP_CONF_DIR在您的Hadoop配置文件夹中定义环境变量,或者在代码中添加以下两行:config.addResource(new Path("/HADOOP_HOME/conf/core-site.xml"));config.addResource(new Path("/HADOOP_HOME/conf/hdfs-site.xml"));如果不添加它,则客户端将尝试写入本地FS,从而导致权限被拒绝的异常。

慕森卡

请尝试以下方法。FileSystem fs = path.getFileSystem(conf);SequenceFile.Writer inputWriter = new SequenceFile.Writer(fs, conf, path, LongWritable.class, MyWritable.class);inputWriter.append(new LongWritable(uniqueId++), new MyWritable(data));inputWriter.close();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java