java创建文件并写入hdfs
在网上找了好几个java写入hdfs的,都是用IOUtils.copy()写入的,最后找到了不是用IOUtils.copy()写入的,赶紧自己整理一下。
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
public class testCreate {
public static void main(String[] args)
throws URISyntaxException, IOException, InterruptedException {
FileSystem fileSystem=FileSystem.get(
new URI("hdfs://172.0.0.1:9000"),
new Configuration(),"root"
);
try {
OutputStream output = fileSystem.create(new Path("/test/t1"));
// 使用\t作为分隔符
output.write("1\t1".getBytes("UTF-8"));
output.write("\n".getBytes("UTF-8"));//换行
fileSystem.close();
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
你都会用java了,肯定也会用scala… 嘿嘿。
java写入hdfs - 追加写
如果不能使用创建写,得追加写入,那怎么办呢?
除了第19行,其他代码都不变。
OutputStream output = fileSystem.append(new Path("/test/t1"));
你都会用java了,肯定也会用scala… 嘿嘿。
pom.xml
贴一下pom.xml
<properties>
<hadoop.version>2.6.0</hadoop.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>${hadoop.version}</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>${hadoop.version}</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-hdfs</artifactId>
<version>${hadoop.version}</version>
</dependency>
</dependencies>