除了可以使用系統(tǒng)API進(jìn)行HDFS操作,還可以通過Java的IO流進(jìn)行文件的上傳和下載疑俭。適用于HDFS的自定義操作,其實(shí)API的底層也是使用IO流進(jìn)行操作的。
1. 把本地的文件上傳到HDFS
@Test
public void putFileToHDFS() throws IOException, URISyntaxException, InterruptedException {
// 1 獲取fs對象
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), conf, "lg");
// 2 獲取輸入流
FileInputStream fis = new FileInputStream(new File("e:/cunzhang.txt"));
// 3 獲取輸出流
FSDataOutputStream fos = fs.create(new Path("/school/shizhang.txt"));
// 4 流對拷
IOUtils.copyBytes(fis, fos, conf);
// 5 關(guān)閉資源
IOUtils.closeStream(fos);
IOUtils.closeStream(fis);
fs.close();
}
2. 把HDFS的文件下載到本地
@Test
public void getFileFromHDFS() throws URISyntaxException, IOException, InterruptedException {
// 1 獲取fs對象
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), conf, "lg");
// 2 獲取輸入流
FSDataInputStream fis = fs.open(new Path("/school/shizhang.txt"));
// 3 獲取輸出流
FileOutputStream fos = new FileOutputStream(new File("/Users/manfestain/Workspace/java/Hadoop/hadoop101/src/main/resources/LocalFile/shizhang.txt"));
// 4 流對拷
IOUtils.copyBytes(fis, fos, conf);
// 5 關(guān)閉資源
IOUtils.closeStream(fos);
IOUtils.closeStream(fis);
fs.close();
}
3. 文件的定位讀取硕糊,我們的HDFS上有一個(gè)288M的文件hadoop-2.7.7.tar.gz,該文件分為兩部分存儲在磁盤上(塊的大小為128M)腊徙,我們可以通過客戶端分別將第一部分和第二部分下載到本地简十。
第一部分的數(shù)據(jù)為128M,第二部分的數(shù)據(jù)為60M撬腾,下面分別下載:
3.1 下載第一塊數(shù)據(jù)
@Test
public void readFileSeek1() throws URISyntaxException, IOException, InterruptedException {
// 1獲取fs對象
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), conf, "lg");
// 2 獲取輸入流
FSDataInputStream fis = fs.open(new Path("/hadoop-2.7.7.tar.gz"));
// 3 創(chuàng)建輸出流
FileOutputStream fos = new FileOutputStream(new File("e:/hadoop-2.7.7.tar.gz.part1"));
// 4 流的對拷(只拷貝128M)
byte[] buf = new byte[1024];
for (int i = 0; i < 1024 * 128; i++) {
fis.read(buf);
fos.write(buf);
}
// 5 關(guān)閉資源
IOUtils.closeStream(fos);
IOUtils.closeStream(fis);
fs.close();
}
3.2 下載第二塊數(shù)據(jù)
@Test
public void readFileSeek2() throws IOException, URISyntaxException, InterruptedException {
// 1獲取fs對象
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(new URI("hdfs://hadoop102:9000"), conf, "lg");
// 2 獲取輸入流
FSDataInputStream fis = fs.open(new Path("/hadoop-2.7.7.tar.gz"));
// 3 設(shè)置指定讀取的起點(diǎn)
fis.seek(1024*1024*128);
// 4 獲取輸出流
FileOutputStream fos = new FileOutputStream(new File("e:/LocalFile/hadoop-2.7.7.tar.gz.part2"));
// 4 流的對拷
IOUtils.copyBytes(fis, fos, conf);
// 關(guān)閉資源
IOUtils.closeStream(fos);
IOUtils.closeStream(fis);
fs.close();
}