HDFS 文件上傳
@Test
public void putFileToHDFS() throws Exception {
// 1 獲取文件系統(tǒng)
Configuration configuration = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), configuration, "root");
// 2 創(chuàng)建輸入流
FileInputStream fis = new FileInputStream(new File("/Users/ylj/demo/io.txt"));
// 3 獲取輸出流
FSDataOutputStream fos = fs.create(new Path("/demo/test/io.txt"));
// 4 流對拷
IOUtils.copyBytes(fis, fos, configuration);
// 5 關(guān)閉資源
IOUtils.closeStream(fis);
IOUtils.closeStream(fos);
fs.close();
System.out.println("~~ok~~");
}
HDFS 文件下載
@Test
public void getFileFromHDFS() throws Exception{
// 1 獲取文件系統(tǒng)
Configuration configuration = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), configuration, "root");
// 2 獲取輸人流
FSDataInputStream fis = fs.open(new Path("/demo/test/io.txt"));
// 3 獲取輸出流
FileOutputStream fos = new FileOutputStream(new File("/Users/ylj/demo/io_bak.txt"));
// 4 流的對拷
IOUtils.copyBytes(fis, fos, configuration);
// 5 關(guān)閉資源
IOUtils.closeStream(fis);
IOUtils.closeStream(fos);
fs.close();
System.out.println("~~ok~~");
}
定位文件讀取
@Test
public void readFileSeek1() throws Exception {
// 1 獲取文件系統(tǒng)
Configuration configuration = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), configuration, "root");
// 2 獲取輸入流
FSDataInputStream fis = fs.open(new Path("/test/demo/hadoop-2.7.2.tar.gz"));
// 3 創(chuàng)建輸出流
FileOutputStream fos = new FileOutputStream(new File("/Users/ylj/demo/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 關(guān)閉資源
IOUtils.closeStream(fis);
IOUtils.closeStream(fos);
fs.close();
System.out.println("~~ok~~");
}
@Test
public void readFileSeek2() throws Exception {
// 1 獲取文件系統(tǒng)
Configuration configuration = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), configuration,"root");
// 2 打開輸入流
FSDataInputStream fis = fs.open(new Path("/test/demo/hadoop-2.7.2.tar.gz"));
// 3 定位輸入數(shù)據(jù)位置
fis.seek(1024 * 1024 * 128);
// 4 創(chuàng)建輸出流
FileOutputStream fos = new FileOutputStream(new File("/Users/ylj/demo/hadoop-2.7.2.tar.gz.part2"));
// 5 流的對拷
IOUtils.copyBytes(fis, fos, configuration);
// 6 關(guān)閉資源
IOUtils.closeStream(fis);
IOUtils.closeStream(fos);
fs.close();
System.out.println("~~ok~~");
}
文件合并
cat hadoop-2.7.2.tar.gz.part2 >> hadoop-2.7.2.tar.gz.part1