讀取HDFS 系統中資料

來源:互聯網
上載者:User

1:使用java.net.url 不過需要轉換,這是最間的那的一種,有缺陷

public class URLCat {/** * @param args */static{URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory());  // 將hdfs 格式的url 轉換成系統能夠識別的}public static void main(String[] args) throws MalformedURLException, IOException {// TODO Auto-generated method stubInputStream in = null;try{in = new URL(args[0]).openStream();IOUtils.copy(in, System.out);}finally{IOUtils.closeQuietly(in);}}}

2 使用 FileSystem API ,hadoop 內建的FileSystem API 實現hdfs 到本地系統的轉換:

// cc FileSystemCat Displays files from a Hadoop filesystem on standard output by using the FileSystem directlyimport java.io.InputStream;import java.net.URI;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.FileSystem;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.IOUtils;// vv FileSystemCatpublic class FileSystemCat {  public static void main(String[] args) throws Exception {    String uri = args[0];    Configuration conf = new Configuration();    FileSystem fs = FileSystem.get(URI.create(uri), conf); // 設定filesystem 的路徑為:hdfs://localhost:9000 會從uri 提取出上面的路徑   預設的hdfs 路徑為file:\\\    System.out.println("URI.create(uri) = " + URI.create(uri) );  //    FileSystem fs = FileSystem.get(conf);  這樣是不行的      System.out.println(fs.getUri().toString()); //可以看出filesystem.get 提取整個檔案系統的uri    InputStream in = null;    try{          in = fs.open(new Path(args[0]));     // 建立輸出資料流 這裡就可以使用hdfs 的uri 來進行讀取了      IOUtils.copyBytes(in, System.out, 4096, false);    } finally {      IOUtils.closeStream(in);//關閉之    }  }}// ^^ FileSystemCat

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.