JAVA上傳檔案至HDFS程式碼及對應jar包
阿新 • • 發佈:2019-01-29
最近需要將本地採集到的檔案上傳到遠端伺服器的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的檢視介面