Accessing files in HDFS using Java

前端 未结 1 579
余生分开走
余生分开走 2021-01-01 01:25

I am trying to access a file in the HDFS using Java APIs, but everytime I am getting File Not Found. Code which I am using to access is :-

Configuration conf         


        
相关标签:
1条回答
  • 2021-01-01 01:34

    Here is code fragment originally posted in context of answer to this question. It should solve your question too despite intention of original question was different. Main point in your code is you have issues starting from scheme (file://). Please check fs.defaultFS variable in your configuration.

    package org.myorg;
    
    import java.security.PrivilegedExceptionAction;
    
    import org.apache.hadoop.conf.*;
    import org.apache.hadoop.security.UserGroupInformation;
    import org.apache.hadoop.fs.Path;
    import org.apache.hadoop.fs.FileSystem;
    import org.apache.hadoop.fs.FileStatus;
    
    public class HdfsTest {
    
        public static void main(String args[]) {
    
            try {
                UserGroupInformation ugi
                    = UserGroupInformation.createRemoteUser("hbase");
    
                ugi.doAs(new PrivilegedExceptionAction<Void>() {
    
                    public Void run() throws Exception {
    
                        Configuration conf = new Configuration();
                        conf.set("fs.defaultFS", "hdfs://1.2.3.4:8020/user/hbase");
                        conf.set("hadoop.job.ugi", "hbase");
    
                        FileSystem fs = FileSystem.get(conf);
    
                        fs.createNewFile(new Path("/user/hbase/test"));
    
                        FileStatus[] status = fs.listStatus(new Path("/user/hbase"));
                        for(int i=0;i<status.length;i++){
                            System.out.println(status[i].getPath());
                        }
                        return null;
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题