7、HDFS輸入輸出流


HDFS的輸入輸出流用於對HDFS文件進行字節的讀取或寫入。

1、HDFS IO文件寫入

把windows本地文件通過HDFS的輸出流寫到HDFS文件中。

@Test
public void testHDFSIoOutput() throws IOException, InterruptedException, URISyntaxException {
	Configuration conf = new Configuration();
	FileSystem fs = FileSystem.get(new URI("hdfs://192.168.85.137:9000"), conf, "root");
	/*創建一個輸入流,用於讀取windows本地文件*/
	FileInputStream in = new FileInputStream("D:/tmp/test.txt");
	/*創建一個HDFS輸出流,用於向HDFS文件中寫入內容*/
	FSDataOutputStream out = fs.create(new Path("/user/lzj/test.txt"));
	/*字節拷貝*/
	IOUtils.copyBytes(in, out, conf);
	IOUtils.closeStream(in);
	IOUtils.closeStream(out);
	fs.close();
}

執行代碼塊,把本地D:/tmp/test.txt文件上傳到了HDFS文件/user/lzj/test.txt中。

2、HDFS IO文件讀取

把HDFS系統中的文件通過HDFS的輸入流讀取到本地磁盤中。

@Test
public void testHDFSIoInput() throws IOException, InterruptedException, URISyntaxException {
	Configuration conf = new Configuration();
	FileSystem fs = FileSystem.get(new URI("hdfs://192.168.85.137:9000"), conf, "root");
	/*創建HDFS輸入流,用於從HDF文件讀取內容S*/
	FSDataInputStream in = fs.open(new Path("/user/lzj/myfile.txt"));
	/*創建本地輸出流,用於向windows本地文件寫入內容*/
	FileOutputStream out = new FileOutputStream("D:/tmp/myfile.txt");
	IOUtils.copyBytes(in, out, conf);
	IOUtils.closeStream(in);
	IOUtils.closeStream(out);
	fs.close();
}

執行代碼後,HDFS中的/user/lzj/myfile.txt文件被拷貝到了本地D:/tmp/myfile.txt。

3、HDFS IO定位讀取

當HDFS執行輸入流操作時,可以指定開始讀取的位置。

	@Test
	public void testHDFSIoSeek() throws IOException, InterruptedException, URISyntaxException {
		Configuration conf = new Configuration();
		FileSystem fs = FileSystem.get(new URI("hdfs://192.168.85.137:9000"), conf, "root");
		/*創建HDFS輸入流,用於從HDF文件讀取內容S*/
		FSDataInputStream in = fs.open(new Path("/tools/jkd/jdk-1.8.0.jar"));
		/*定位輸入數據起始位置*/
		in.seek(1024*1028);
		/*創建本地輸出流,用於向windows本地文件寫入內容*/
		FileOutputStream out = new FileOutputStream("D:/tools/jdk/jdk-1.8.0.jar.tmp");
		IOUtils.copyBytes(in, out, conf);
		IOUtils.closeStream(in);
		IOUtils.closeStream(out);
		fs.close();
	}

執行代碼塊後,HDFS開始從指定位置1024*1028複製文件到本地磁盤中。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章