關于hdfs的基本操作,
讀取,上傳,下載下傳,删除:
- hdfs檔案讀取
package org.apache.hadoop.studyhdfs;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
public class hdfsAPI {
// 擷取配置檔案并得到檔案系統的方法
public static FileSystem getfs() throws IOException{
// get Configreation:擷取配置檔案
Configuration conf =new Configuration();
//也可以通過如下來配置環境 //conf.set("fs.defaultFS", "xxx");
// getFileSystem:擷取檔案系統
FileSystem fs =FileSystem.get(conf);
return fs;
}
//hdfs檔案讀取
public static void main(String[] args) throws IOException {
// step 1:get FileSystem擷取檔案系統
FileSystem fs =getfs();
FSDataInputStream instream =null; //new一個輸入流對象
// step 2: read path設定讀取路徑
Path readpath =new Path("/data/inputFiles/wc.input"); //給Path對象設定值讀入路徑
// step 3: open inputStream打開輸入流
try{
instream = fs.open(readpath);
IOUtils.copyBytes(instream, System.out, ,false); //将讀取檔案輸出
}catch(Exception e){
e.printStackTrace();
}finally{
// step 4: closeStream 關閉輸入流
IOUtils.closeStream(instream);
}
}
}
- hdfs檔案上傳
public static void main(String[] args) throws IOException {
// step 1 :擷取檔案系統
FileSystem fs = getfs();
// step 2 :擷取本地檔案路徑local File
File infile =new File("/opt/datafile/wc.input");
// step 3:擷取上傳路徑 put File
Path outfile =new Path("/data/inputFiles/input02");
FileInputStream instream =null;
FSDataOutputStream outStream=null;
try{
// step 4 :打開輸入流open inputStream
instream = new FileInputStream(infile);
// step 5:打開輸出流open outputStream
outStream = fs.create(outfile);
IOUtils.copyBytes(instream, outStream, , false);
System.out.print("-put Files success");
}catch(Exception e){
e.printStackTrace();
}finally{
// step 6 : 關閉流
IOUtils.closeStream(instream);
IOUtils.closeStream(outStream);
}
}
-hdfs檔案下載下傳
public static void main(String[] args) throws IOException {
// step 1 :擷取檔案系統
FileSystem fs =getfs();
//step 2 :擷取下載下傳檔案位址,以及下載下傳到本機的位址
fs.copyToLocalFile(new Path("/data/core.xml"), new Path("/opt/datafile/"));
//step 3 :關閉檔案系統
fs.close();
System.out.print("download success");
}
`
-hdfs檔案删除
// delete files
public static void main(String[] args) throws IOException {
step 1: 擷取檔案系統
FileSystem fs =getfs();
step 2 : 擷取要删除的檔案
Path path =new Path("/data/core.xml");
step 3 :對檔案進行判斷
if(fs.exists(path)){
fs.delete(path,true); //判斷正确則删除并輸出success
System.out.print("success,deleted files");
}else {
System.out.print("error delete false");//判斷失敗則輸出error資訊
}
}