2014-02-25 15 views
0

如何運行這個簡單的Java程序從存儲在HDFS中的目錄/文字中的文本文件中讀取字節?我需要爲此目的創建一個jar文件嗎?請建議。使用Java以編程方式讀取存儲在HDFS中的文本文件的內容

 import java.io.*; 
     import java.net.MalformedURLException; 
     import java.net.URL; 
     import org.apache.hadoop.*; 
     import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; 
    public class filesystemhdfs 
    { 
    public static void main(String args[]) throws MalformedURLException, IOException 
    { 

     byte[] b=null; 
    InputStream in=null; 
    in=new URL("hdfs://localhost/words/file").openStream(); 
    in.read(b); 
    System.out.println(""+b); 
    for(int i=0;i<b.length;i++) 
    { 
     System.out.println("b[i]=%d"+b[i]); 
     System.out.println(""+(char)b[i]); 
    } 

    } 
    } 

回答

1

首先,您需要告訴JVM有關URLs對象中的HDFS方案。這是通過做:

URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory()); 

編譯Java類之後,您需要使用的Hadoop命令:

hadoop filesystemhdfs 

的Hadoop帶有一個方便IOUtils。它會爲你減輕很多東西。

2

您可以使用HDFS API,這可以從本地運行:

Configuration configuration = new Configuration(); 
     configuration.set("fs.defaultFS", "hdfs://namenode:8020"); 
     FileSystem fs = FileSystem.get(configuration); 
Path filePath = new Path(
       "hdfs://namenode:8020/PATH"); 

     FSDataInputStream fsDataInputStream = fs.open(filePath); 
0

不能讀取HDFS文件,作爲一個普通的文件系統Java支持。您需要爲此使用HDFS java AP

public static void main(String a[]) { 
    UserGroupInformation ugi 
    = UserGroupInformation.createRemoteUser("root"); 

    try { 


     ugi.doAs(new PrivilegedExceptionAction<Void>() { 

      public Void run() throws Exception { 

       Configuration conf = new Configuration(); 
        //fs.default.name should match the corresponding value 
        // in your core-site.xml in hadoop cluster 
       conf.set("fs.default.name","hdfs://hostname:9000"); 
       conf.set("hadoop.job.ugi", "root"); 

       readFile("words/file",conf) 

       return null; 
      } 
     }); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

} 

public static void readFile(String file,Configuration conf) throws IOException { 
    FileSystem fileSystem = FileSystem.get(conf); 

    Path path = new Path(file); 
    if (!ifExists(path)) { 
     System.out.println("File " + file + " does not exists"); 
     return; 
    } 

    FSDataInputStream in = fileSystem.open(path); 

    BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
    String line = null; 
    while((line = br.readLine())!= null){ 
     System.out.println(line); 
    } 
    in.close(); 
    br.close(); 
    fileSystem.close(); 
} 
    public static boolean ifExists(Path source) throws IOException { 

    FileSystem hdfs = FileSystem.get(conf); 
    boolean isExists = hdfs.exists(source); 
    System.out.println(isExists); 
    return isExists; 
} 

在這裏,我從遠程計算機嘗試,這就是爲什麼我使用UserGroupInformation並在PrivilegedExceptionAction run方法編寫代碼。如果你在本地系統,你可能不需要它。 HTH!

+0

請同時告訴如何在程序上面運行? – user2200278

+0

將上面的代碼放在一個類中,然後在classpath中添加hadoop jar。 –

相關問題