hadoop入门----hdfs客户端的文件操作

问题

思路

客户端的操作就是hdfs的api操作,我用的编译器是idea。除了追加到文件到头以外,其它都是用hdfs自带的api。追加到文件头需要转换下思路,具体思路在代码。

代码

package com.xiao.hdfs;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.IOUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.*;
import java.net.URI;
import java.util.Scanner;

public class TestHDFS {
    private URI uri;
    private Configuration conf;
    private String user;
    private FileSystem fs;
    // 会在test方法执行之前执行,初始变量
    @Before
    public void init(){
        uri = URI.create("hdfs://hadoop42:8020");
        conf = new Configuration();
        user = "xiao";
        try {
            fs = FileSystem.get(uri,conf,user);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    // 会在test方法执行完毕之后,释放资源
    @After
    public void destroy(){
        try {
            fs.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //上传文件
    @Test
    public void testUpload(){
        /**
         * @param delSrc 是否删除源文件
         * @param overwrite 是否覆盖同名文件
         * @param src 本地路径
         * @param dst 上传路径
         *
         */
        try {
            fs.copyFromLocalFile(false,true,
                    new Path("D:/code/testFile/hadoop学习指南.txt"),
                    new Path("/testHDFS")
                    );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 新建文件
    @Test
    public void createFile(){
        try {
            Scanner scanner = new Scanner(System.in);
            System.out.print("请输入要创建的文件名及所在目录:");
            String strPath = scanner.next();
            FSDataOutputStream out = fs.create(new Path(strPath),true);
            System.out.println("创建成功");
            out.close();
        } catch (Exception e) {
            System.out.println("创建失败:路径错误!");;
        }
    }

    // 文件读取
    @Test
    public void openFile(){
        try {
            Scanner scanner = new Scanner(System.in);
            System.out.print("请输入要读取的文件路径:");
            String str_path = scanner.next();
            FSDataInputStream open = fs.open(new Path(str_path));
            BufferedReader d = new BufferedReader(new InputStreamReader(open));
            String line = null;
            while ((line = d.readLine()) != null) {
                String[] strarray = line.split(" ");
                for (int i = 0; i < strarray.length; i++) {
                    System.out.print(strarray[i]+" ");
                }
                System.out.println(" ");
            }
            d.close();
            open.close();
        } catch (IOException e) {
            System.out.println("文件路径错误!");;
        }
    }

    @Test
    public void editFile() {
            Scanner scanner = new Scanner(System.in);
            try {
                System.out.print("请输入你要追加的文件路径:");
                String strPath = scanner.next();
                FSDataOutputStream out = fs.append(new Path(strPath));
                System.out.println("请输入你要追加的内容...");
                String content = scanner.next();
                System.out.print("请输入你要追加到文件的头还是尾:1、头  2、尾             ");
                int n = scanner.nextInt();
                if (n==2){
                    out.write(content.getBytes());
                    out.close();
                }else {
                    /**
                     *追加文件到头的整体思想是,先创建一个文件,然后将我们的追加的内容添加到该文件里,然后
                     * 在把被追加的文件内容追加到新的文件里,最后在把新的文件覆盖之前旧的文件。
                     */
                    FSDataInputStream open = fs.open(new Path(strPath));
                    FSDataOutputStream fsout = fs.create(new Path("/temp.txt"),true);
                    fsout.write(content.getBytes());
                    IOUtils.copyBytes(open,fsout,fs.getConf());
                    open.close();
                    fsout.close();
                    FSDataOutputStream fsDataOutputStream = fs.create(new Path(strPath));
                    FSDataInputStream open1 = fs.open(new Path("/temp.txt"));
                    IOUtils.copyBytes(open1,fsDataOutputStream,fs.getConf());
                    fsDataOutputStream.close();
                    open1.close();
                }

                System.out.print("请输入你要保存的位置:");
                String savePath = scanner.next();
                fs.rename(new Path(strPath),new Path(savePath));

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

    }

    // 展示功能
    public void show(){
        System.out.println("选择功能:");
        System.out.println("1.创建");
        System.out.println("2.打开");
        System.out.println("3.编辑");
        System.out.println("请输入...");
    }
    public static void main(String[] args) {
        //实例化对象
        TestHDFS t = new TestHDFS();
        // 初始化
        t.init();
        Scanner scanner = new Scanner(System.in);
        //是否退出
        boolean flag = true;
        while (flag){
            t.show();
            int n = scanner.nextInt();
         switch (n){
             case 1:t.createFile();break;
             case 2:t.openFile();break;
             case 3:t.editFile();break;
             default:t.destroy();flag = false;break;
         }
        }
    }
}


运行结果








posted @ 2020-10-16 15:20  littlemelon  阅读(197)  评论(0编辑  收藏  举报