国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

HDFS Java API再探

2019-11-08 00:56:46
字體:
來源:轉載
供稿:網友

有時對于MaPReduce等框架來說,需要有一套更底層的API來獲取某個指定文件中的一部分數據,而不是一整個文件。一方面來說,獲取整個文件是對網絡的很大壓力;另一方面,可能整個文件非常大,客戶端也存不下。因此這篇博客再體驗一下HDFS的流式API。

測試類代碼

package tech.mrbcy.bigdata.hdfs;import java.io.FileInputStream;import java.net.URI;import java.util.Iterator;import java.util.Map.Entry;import org.apache.commons.io.IOUtils;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.FSDataOutputStream;import org.apache.hadoop.fs.FileSystem;import org.apache.hadoop.fs.LocatedFileStatus;import org.apache.hadoop.fs.Path;import org.apache.hadoop.fs.RemoteIterator;import org.junit.Before;import org.junit.Test;public class HdfsClientDemo { private FileSystem fs; Configuration conf; @Before public void init() throws Exception{ conf = new Configuration(); fs = FileSystem.get(new URI("hdfs://amaster:9000"), conf, "root"); }}

用流方式上傳文件

@Testpublic void testUploadWithStream() throws Exception{ FSDataOutputStream out = fs.create(new Path("/access_stream.log"), true); FileInputStream fin = new FileInputStream("c:/access.log"); IOUtils.copy(fin, out);}

用流方式下載文件

@Testpublic void testDownloadWithStream() throws Exception{ FSDataInputStream in = fs.open(new Path("/access_stream.log")); FileOutputStream out = new FileOutputStream("d:/access_stream.log"); IOUtils.copy(in, out);}

用流方式讀指定長度的文件

@Testpublic void testRandomAccess() throws Exception{ FSDataInputStream in = fs.open(new Path("/access_stream.log")); FileOutputStream out = new FileOutputStream("d:/access_stream.log"); IOUtils.copyLarge(in, out, 1*1024*1024, 1*1024*1024); // 從1M位置開始讀,讀1M}

如圖所示:

在控制臺打印HDFS文件內容

@Testpublic void testCat() throws Exception{ FSDataInputStream in = fs.open(new Path("/access_stream.log")); IOUtils.copy(in,System.out);}

獲取文件塊信息

@Testpublic void testGetFileBlock() throws Exception{ FileStatus fileStatus = fs.getFileStatus(new Path("/hadoop-2.7.3.tar.gz")); BlockLocation[] blockLocations = fs.getFileBlockLocations(fileStatus, 0, fileStatus.getLen()); for (BlockLocation bl : blockLocations) { System.out.println("block-length:" + bl.getLength() + "--" + "block-offset:" + bl.getOffset()); String[] hosts = bl.getHosts(); for (String host : hosts) { System.out.println(host); } }}

輸出結果為:

block-length:134217728--block-offset:0anode1.mrbcy.techanode2.mrbcy.techblock-length:79874467--block-offset:134217728anode2.mrbcy.techanode1.mrbcy.tech
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 西畴县| 罗源县| 林西县| 句容市| 勐海县| 洛宁县| 金湖县| 普兰县| 图木舒克市| 巫溪县| 凉山| 临沂市| 丹寨县| 浑源县| 东乌珠穆沁旗| 永靖县| 丰顺县| 乐昌市| 洪泽县| 清涧县| 常宁市| 上林县| 平遥县| 龙门县| 铜川市| 天祝| 凭祥市| 木兰县| 仲巴县| 道真| 托里县| 京山县| 库伦旗| 沙田区| 曲水县| 洪泽县| 井研县| 吴堡县| 邮箱| 多伦县| 天津市|