美文网首页
java api操作HDFS

java api操作HDFS

作者: 一条IT | 来源:发表于2018-12-28 09:54 被阅读16次

    如果是使用maven的话,导入如下依赖即可,否则需要在解压好的hadoop文件夹下找到common文件夹和hdfs文件夹下的jar包

    <dependency>
        <groupId>org.apache.hadoop</groupId>
       <artifactId>hadoop-client</artifactId>
        <version>2.8.3</version>
    </dependency>
    

    如果在运行过程中出现以下问题:

    Caused by: org.apache.hadoop.ipc.RemoteException(org.apache.hadoop.security.AccessControlException): Permission denied: user=ttc, access=WRITE, inode="/":root:supergroup:drwxr-xr-x
    

    需要在之前写入root。

    //填写上传文件的用户名是root,默认administrator没有这个权限!
    System.setProperty("HADOOP_USER_NAME", "root") ;
    
    public class App 
    {
        Configuration configuration;
        FileSystem    fileSystem;
        @BeforeTest
        public void  init() throws IOException {
            //填写上传文件的用户名是root,默认administrator没有这个权限!
            System.setProperty("HADOOP_USER_NAME", "root");
            configuration = new Configuration();
            configuration.set("fs.defaultFS","hdfs://hadoop02:8020");
            fileSystem = FileSystem.get(configuration);
        }
        @Test
        public void testUpload() throws IOException {
            System.out.println("hello");
            //将本地的文件上传到hdfs上面。第一个Path是本地的路径,第二个path是hdfs里面的路径。
            fileSystem.copyFromLocalFile(new Path("d:/mylog.txt"),new Path("/mylog.txt"));
            fileSystem.close();
            System.out.println("成功");
        }
        @Test
        public void testDownload()throws IOException{
            //将hdfs里面的下载到本地中,第一个TRUE是代表删除源文件,false不删除源文件。第一个path是hdfs里面的路径;第二个path是本地的路径,ture是copy到本地系统,false是拷贝到hdfs系统中
            fileSystem.copyToLocalFile(true,new Path("/world.txt"),new Path("d://copymylog.txt"),true);
            fileSystem.close();
        }
        @Test
        public void getconfig(){
            Iterator<Map.Entry<String, String>> iterator = configuration.iterator();
            while(iterator.hasNext()){
                Map.Entry<String,String> entry = iterator.next();
                System.out.println(entry.getKey()+":"+entry.getValue());
            }
        }
    
    }
    

    相关文章

      网友评论

          本文标题:java api操作HDFS

          本文链接:https://www.haomeiwen.com/subject/fntslqtx.html