輸出倒逼輸入
HDFS客戶端操作 --- IO流操作
HDFS檔案上傳
@Test
public void putFileToHDFS() throws IOException, InterruptedException, URISyntaxException {
// 1 獲取檔案系統
Configuration configuration = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), configuration, "zhutiansama");
// 2 創建輸入流
FileInputStream fis = new FileInputStream(new File("e:/data.txt"));
// 3 獲取輸出流
FSDataOutputStream fos = fs.create(new Path("/data.txt"));
// 4 流對拷,關鍵
IOUtils.copyBytes(fis, fos, configuration);
// 5 關閉資源
IOUtils.closeStream(fos);
IOUtils.closeStream(fis);
fs.close();
}
HDFS檔案下載
// 檔案下載
@Test
public void getFileFromHDFS() throws IOException, InterruptedException, URISyntaxException{
// 1 獲取檔案系統
Configuration configuration = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), configuration, "zhutiansama");
// 2 獲取輸入流
FSDataInputStream fis = fs.open(new Path("/data.txt"));
// 3 獲取輸出流,注意Input是從哪里輸入,Output是輸出到哪里
FileOutputStream fos = new FileOutputStream(new File("e:/data.txt"));
// 4 流的對拷
IOUtils.copyBytes(fis, fos, configuration);
// 5 關閉資源
IOUtils.closeStream(fos);
IOUtils.closeStream(fis);
fs.close();
}
定位檔案讀取
1.下載第一塊檔案資料【檔案如果過大就會分塊存盤,所以需要分塊讀取】
@Test
public void readFileSeek1() throws IOException, InterruptedException, URISyntaxException{
// 1 獲取檔案系統
Configuration configuration = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), configuration, "zhutiansama");
// 2 獲取輸入流
FSDataInputStream fis = fs.open(new Path("/hadoop-2.7.2.tar.gz"));
// 3 創建輸出流
FileOutputStream fos = new FileOutputStream(new File("e:/hadoop-2.7.2.tar.gz.part1"));
// 4 流的拷貝
byte[] buf = new byte[1024];
for(int i =0 ; i < 1024 * 128; i++){
fis.read(buf);
fos.write(buf);
}
// 5關閉資源
IOUtils.closeStream(fis);
IOUtils.closeStream(fos);
}
2.下載第二塊檔案資料
@Test
public void readFileSeek2() throws IOException, InterruptedException, URISyntaxException{
// 1 獲取檔案系統
Configuration configuration = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), configuration, "zhutiansama");
// 2 打開輸入流
FSDataInputStream fis = fs.open(new Path("/hadoop-2.7.2.tar.gz"));
// 3 定位輸入資料位置
fis.seek(1024*1024*128);
// 4 創建輸出流
FileOutputStream fos = new FileOutputStream(new File("e:/hadoop-2.7.2.tar.gz.part2"));
// 5 流的對拷
IOUtils.copyBytes(fis, fos, configuration);
// 6 關閉資源
IOUtils.closeStream(fis);
IOUtils.closeStream(fos);
}
3.合并兩塊檔案
按住shift打開cmd,對資料進行合并
type hadoop-2.7.2.tar.gz.part2 >> hadoop-2.7.2.tar.gz.part1
合并完成后,將hadoop-2.7.2.tar.gz.part1重新命名為hadoop-2.7.2.tar.gz即可
相關資料

本文配套GitHub:https://github.com/zhutiansama/FocusBigData
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/150248.html
標籤:Java
