02 HDFS 文件读写代码详解

     

  1. 新建一个JAVA项目
  2. 在项目上添加jar包   jar包目录在你安装的hadoop目录下的/hdfs-hadoop-share—common(lib )和hdfs(lib)(即common和hdfs下的所有jar包)
  3. 添加两个配置文件到项目 的src目 录下 ( /hdfs/hadoop/etc/hadoop/)                                 core-site.xml                                                                                                                       hdfs-site.xml
  4. 右击项目的src目录-新建类  FileReader.java,源码如下
    import org.apache.hadoop.conf.Configuration;
    import org.apache.hadoop.fs.FSDataInputStream;
    import org.apache.hadoop.fs.FileSystem;
    import org.apache.hadoop.fs.Path;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    public class FileReader
    {
        public static void main(String[] args)throws IOException
        {
      //加载配置信息
            Configuration conf = new Configuration();
            conf.set("fs.defaultFS","hdfs://hacluster");
    //指定读取的路径
            Path path = new Path("/tenant/user06/a.txt");
    //获取文件系统
            FileSystem fs  = FileSystem.get(conf);
      //打开指定的路径
          FSDataInputStream input =  fs.create (path);
    //封装为缓冲文本读取
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
    //读取一行记录
           String str =  reader.readLine();
    //如果记录不为空
           while(str!=null)
           {
    //打印输出
               System.out.println(str);
    //读取一行记录
               str =  reader.readLine();
           }
    //关闭流
           input.close();
           reader.close();
    
    //以FSDataInputStream流的方式读取
    //      byte[] b = new byte[10];
    // 读取到字符数组中
    //      input.read(b);
    //循环字节数组
    //      for(int i = 0;i<b.length;i++)
    //      {
    //打印数组的每个字符
    //          System.out.println((char)b[i]);
    //      }
    
    
    
        }
    }
    

    8、文件写入

    package com.huawei;
    import org.apache.hadoop.conf.Configuration;
    import org.apache.hadoop.fs.FSDataOutputStream;
    import org.apache.hadoop.fs.FileSystem;
    import org.apache.hadoop.fs.Path;
    
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    
    public class FileWriter
    {
        public static void main(String[] args)throws IOException
    {
    //加载配置信息
    
            Configuration conf = new Configuration();
            conf.set("fs.defaultFS", "hdfs://hacluster");
    //指定写入的路径
    
            Path path = new Path("/tenant/user06/a.txt");
    //获得文件系统
            FileSystem fs = FileSystem.get(conf);
    //建立流连接
            //FSDataOutputStream output = fs.create(path);
         // 也可以在原来的文件上做追加   
    FSDataOutputStream output = fs.append(path);
    //封装为缓冲文本写入
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
    //写入字符串
            writer.write("\naaa\nbbbb \n ccc");
    //写入一个空行
           // writer.newLine();
           // writer.write("hello world");
    //刷新缓冲区,写入文件
            writer.flush();
    // 关闭流
            output.close();
            writer.close();
            System.out.println("write successs");
    
    
        }
    }
    

    9、文件操作

    package com.huawei;
    
    import org.apache.hadoop.conf.Configuration;
    import org.apache.hadoop.fs.FileSystem;
    import org.apache.hadoop.fs.*;
    
    import java.io.IOException;
    
    public class FileTest
    {
    //声明文件系统
        public static FileSystem fs;
    
        public FileTest(FileSystem fs)
        {
            this.fs = fs;
        }
        //创建目录
    public  void mkDIR(String filepath)throws IOException
    {
    //设置目录的路径
            Path path = new Path(filepath);
    //按指定路径创建目录
            fs.mkdirs(path);
    //关闭文件系统
            fs.close();
        }
    //删除目录
     public void deleDIR(String filepath,String s)throws  IOException
      {
    //设置目录的路径
    
           Path path = new Path(filepath);
    //如果第二个参数为-r,则递归删除
           if(s.equals("-r"))
           {//则递归删除
    
               fs.delete(path,true);
           }
           else
           {//否则不会递归删除
    
               fs.delete(path,false);
           }
    //关闭文件系统
           fs.close();
    
           System.out.println("delete dir OK");
        }
    
        //创建文件
    public void createFile(String fileName)throws  IOException
    {
    //创建给定名称的文件
            fs.create(new Path(fileName));
            fs.close();
            System.out.println("create file OK");
        }
    //上传文件
    public void put(String localPath,String hdfsPath)throws  IOException
    {
    // 本地路径
            Path local = new Path(localPath);
    //hdfs路径
            Path hdfs = new Path(hdfsPath);
    //上传
            fs.copyFromLocalFile(local,hdfs);
            fs.close();
            System.out.println("put file OK");
    
        }
    
        // 下载文件
    public void get(String hdfsPath,String localPath)throws  IOException
    {
    // 本地路径
    
            Path local = new Path(localPath);
    //hdfs路径
    
            Path hdfs = new Path(hdfsPath);
    //下载
            fs.copyToLocalFile(hdfs,local); ;
            fs.close();
            System.out.println("get file OK");
    
        }
        //重命名
    public void fileRename(String oldFile,String newFile)throws  IOException
    {
    将oldFile改为newFile名称
            fs.rename(new Path(oldFile),new Path(newFile));
            fs.close();
            System.out.println("rename file OK");
        }
    //文件的详细信息
     public void listFile(String fpath)throws IOException
        {
    //根据给定的路径返回文件列表
           RemoteIterator<LocatedFileStatus>  listfile = fs.listFiles(new Path(fpath),true);
    //递归显示所有文件
           while(listfile.hasNext())
           {
               LocatedFileStatus fileStatus = listfile.next();
    //文件的名称
               System.out.println("name:"+fileStatus.getPath().getName());
    //文件的副本数
               System.out.println("repla"+fileStatus.getReplication());
    //文件的权限
               System.out.println("per"+fileStatus.getPermission());
    // 文件的长度
               System.out.println("len"+fileStatus.getLen());
           }
        }
    
    // 主方法,实现方法的调用
    public  static void main(String args[])throws IOException
    {
    // 置配信息
            Configuration conf = new Configuration();
            conf.set("fs.defaultFS","hdfs://hacluster");
             fs  = FileSystem.get(conf);
    
    //实例化类的对象,调用类的方法
            FileTest ft = new FileTest(fs);
    //创建目录
            //ft.mkDIR("/tenant/user06/lyf");
    //创建文件
            //ft.createFile("/tenant/user06/lyf/a.txt");
    //删除目录
            //ft.deleDIR("/tenant/user06/lyf","-r");
    //上传
           // ft.put("/home/user06/Desktop/stu.txt","/tenant/user06/lyf");
    //下载
            //ft.get("/tenant/user06/lyf/a.txt","/home/user06/Desktop/");
    //重命名
            //ft.fileRename("/tenant/user06/lyf/a.txt","/tenant/user06/lyf/b.txt");
    //显示文件的内容
            ft.listFile("/tenant/user06/");
    
        }
    }
    

  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值