我想在 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 中写入吗?
谢谢。
最佳答案
@Tariq 的替代方法是您可以在获取文件系统时传递 URI
import org.apache.hadoop.fs.FileSystem
import org.apache.hadoop.conf.Configuration
import java.net.URI
import org.apache.hadoop.fs.Path
import org.apache.hadoop.util.Progressable
import java.io.BufferedWriter
import java.io.OutputStreamWriter
Configuration configuration = new Configuration();
FileSystem hdfs = FileSystem.get( new URI( "hdfs://localhost:54310" ), configuration );
Path file = new Path("hdfs://localhost:54310/s2013/batch/table.html");
if ( hdfs.exists( file )) { hdfs.delete( file, true ); }
OutputStream os = hdfs.create( file,
new Progressable() {
public void progress() {
out.println("...bytes written: [ "+bytesWritten+" ]");
} });
BufferedWriter br = new BufferedWriter( new OutputStreamWriter( os, "UTF-8" ) );
br.write("Hello World");
br.close();
hdfs.close();
关于java - 使用 Java 在 hdfs 中写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16000840/