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