最近需要将本地采集到的文件上传到远程服务器的HDFS文件系统当中,弄了很久,找代码,找JAR包,很麻烦,记录一下。
源码部分很简单:
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
public class BmTEST {
public static void main(String[] args) throws IOException {
String source ="e:\\TEST/T1.txt"; //本地的测试文件
String des = "hdfs://192.168.8.30:8020/test/test1.txt"; //hdfs当中文件地址
InputStream in = new BufferedInputStream(new FileInputStream(source));
//HDFS读写的配置文件
Configuration conf = new Configuration();
//调用Filesystem的create方法返回的是FSDataOutputStream对象
//该对象不允许在文件中定位,因为HDFS只允许一个已打开的文件顺序写入或追加
FileSystem fs = null;
try {
//fs = FileSystem.get(URI.create(des),conf);这样写默认是使用root进行文件上传,
//是没有上传文件到hdfs的权限的 要使用hdfs账号进行上传
fs = FileSystem.get(URI.create(des),conf,"hdfs");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OutputStream out = fs.create(new Path(des));
IOUtils.copyBytes(in, out, 4096, true);
}
}
需要jar包:
这些包都可以在maven当中查找到
最后附上上传成功后hdfs的查看界面