hdfs——hadoop檔案讀寫操作
阿新 • • 發佈:2019-02-02
在hadoop中,有三大法寶——HDFS,MapReduce,Hbase,但是無論是MapReduce,Hbase還是hadoop中的其他元件如:Hive等他們要處理的資料還是處理完了的資料都是儲存在HDFS中。可見HDFS可以說是hadoop儲存的基礎和核心,因此對HDFS的檔案讀寫操作顯得十分重要。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import org.apache.hadoop.conf.Configuration ;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
public class Test1 {
/*
* 往hdfs中寫資料
*/
public static void writeToHdfs(String filename,String text){
Configuration configuration=new Configuration();
FSDataOutputStream out=null;
String charset="UTF-8";
try {
FileSystem fSystem=FileSystem.get(URI.create(filename),configuration);
Path path=new Path(filename);
if(!fSystem.exists(path)){
//建立檔案資料的輸出流
out=fSystem.create (new Path(filename));
//通過輸出流往hdfs中寫入資料
out.write(text.getBytes(charset),0,text.getBytes(charset).length);
out.write("\n".getBytes(charset),0,"\n".getBytes(charset).length);
out.flush();
}else{
//往檔案中追加資料
out=fSystem.append(path);
out.write(text.getBytes(charset),0,text.getBytes(charset).length);
out.write("\n".getBytes(charset),0,"\n".getBytes(charset).length);
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
}finally{
//關閉輸出流
if(out!=null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*
* 從hdfs中讀取資料
*/
public static void readFromHdfs(String fileName){
Configuration conf=new Configuration();
Path filePath=new Path(fileName);
try {
FileSystem fs=FileSystem.get(URI.create(fileName),conf);
if(fs.exists(filePath)){
String charset="UTF-8";
//開啟檔案資料輸入流
FSDataInputStream fsDataInputStream=fs.open(filePath);
//建立檔案輸入
InputStreamReader inputStreamReader=new InputStreamReader(fsDataInputStream,charset);
String line=null;
//把資料讀入到緩衝區中
BufferedReader reader=null;
reader=new BufferedReader(inputStreamReader);
//從緩衝區中讀取資料
while((line=reader.readLine())!=null){
System.out.println("line="+line);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) {
//String filename="hdfs://119.29.167.178:9000/test";
String filename="/test/file1";
String text="我們很6666";
writeToHdfs(filename,text);
writeToHdfs(filename, "5555555");
readFromHdfs(filename);
}
}
執行結果圖:
往hdfs中寫資料:
讀取hdfs上的資料: