IO练习:对文件目录的读取

描述:对File对象的练习


import java.io.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.*;

/**
 * 文件的读取,目录的递归获取的练习,该练习的效果是打印出某个目录下的文件和目录,并提供用户输入选择文件或目录,如果
 * 是文件,则打印内容;如果是目录,则打印出目录内文件
 * 期间的遇到的问题:中文乱码,读取txt文件中的文字时,不论是按字节流读取,还是字符流,都是乱码
 * 解决:字节流时,要判断是否中文,如果是,要两个字节一起输出;
 * 字符流时,要在创建流时,加上字符编码参数
 */
public class FileDirectoryPractice {

    File root = null;  // 初始文件目录对象
    String path = "";  // 初始目录路径

    Charset charset = Charset.forName("utf-8");  // 不用

    Map allPath = new HashMap<>();

    CharsetEncoder encoder = charset.newEncoder();
    CharsetDecoder decoder = charset.newDecoder();

    FileDirectoryPractice() {

    }

    FileDirectoryPractice(String path) {
        this.path = path;
    }

    /**
     * 解析程序入口
     * @throws Exception
     */
    public void startFile() throws Exception{
        root = new File(path);

        printFileList(root);
    }

    /**
     * 打印信息到控制台
     * @param root 当前文件
     * @throws Exception
     */
    public void printFileList(File root) throws Exception{

        List> fileList = startExpore(root);
        for (Map one : fileList) {
            System.out.println((String) one.get("type")+": "+(String)one.get("name"));
        }
        Scanner sc = new Scanner(System.in);
        System.out.print("请选择(返回上一级请输#last):");
        String selectedType = sc.nextLine();

        while(selectedType == null || selectedType.equals("")) {
            System.out.print("请重新输入(返回上一级请输#last):");
            selectedType = sc.nextLine();
        }

        File selectedRoot = null;

        if ("#last".equals(selectedType)) {
            selectedRoot = root.getParentFile();
        } else {
            for (Map one: fileList) {
                String name = (String) one.get("name");
                if (name.equals(selectedType)) {
                    selectedRoot = (File)one.get(name);
                    break;
                }
            }
        }

        if (selectedRoot == null) {
            System.out.println("不存在该目录!");
        } else {
            if (selectedRoot.isFile()) {
                try {
                    readFile(selectedRoot);
                } catch (Exception e) {
                    throw new Exception("读取文件出错"+e.getMessage());
                }
            } else {
                printFileList(selectedRoot);
            }
        }
    }

    /**
     * 选择文件时,读取文件方法
     * @param root
     * @throws Exception
     */
    public void readFile(File root) throws Exception{
        InputStream in = new FileInputStream(root);
        //printStreamByLine(in);
        printStreamByByte(in);
    }

    /**
     * 字节流方式打印文件内容
     * @param in
     * @throws Exception
     */
    public void printStreamByByte(InputStream in) throws  Exception{
        int b = 0;
        while ((b=in.read()) != -1) {
            if (!(b >=0 && b < 128)) {
                int b2 = in.read();
                System.out.print(new String(new byte[]{(byte)b,(byte)b2},"gbk"));
                continue;
            }
            System.out.print((char)b);
        }

        close(in);
    }

    /**
     * 字符流方式打印文件内容
     * @param in
     * @throws Exception
     */
    public void printStreamByLine(InputStream in) throws Exception {

        BufferedReader fileReader = new BufferedReader(new InputStreamReader(in,"gbk"));
        String content = "";
        while ((content = fileReader.readLine()) != null) {
            System.out.println(content);
        }

        close(fileReader);
        close(in);
    }

    /**
     * 关闭流
     * @param c
     * @throws Exception
     */
    public void close(Closeable c) throws Exception{
        if (c != null) {
            c.close();
        }
    }

    /**
     * 获取当前目录下的所有文件目录
     * @param file
     * @return
     */
    public List> startExpore(File file) {

        List> result = new ArrayList<>();

        if (file == null) return result;

        if (file.isFile()) {
            Map one = exporeDirectory(file);
            result.add(one);
        } else {
            for (File o : Objects.requireNonNull(file.listFiles())) {
                Map fileMap = exporeDirectory(o);
                result.add(fileMap);
            }
        }

        return result;
    }

    /**
     * 判断file的属性并封装起来
     * @param file 文件对象
     * @return 文件封装对象
     */
    private Map exporeDirectory(File file) {

        if (file == null)  return null;

        Map result = new HashMap<>();
        if (file.isFile()) {
            result.put(file.getName(),file);
            result.put("type","file");
            result.put("name",file.getName());
            return result;
        } else  {
            result.put(file.getName(),file);
            result.put("type","directory");
            result.put("name",file.getName());
            return result;
        }

    }

    public String encodeString(String content) {

        CharBuffer charBuffer = CharBuffer.wrap(content);
        String result = "";
        try {
           ByteBuffer byteBuffer = encoder.encode(charBuffer);
           CharBuffer charBuffer1 = decoder.decode(byteBuffer);
           result = charBuffer1.toString();
        } catch (Exception e) {
          e.printStackTrace();
        }

        return result;
    }


    public static void main(String[] args) {

        FileDirectoryPractice fileTest = new FileDirectoryPractice("d://FileTest");

        try {
            fileTest.startFile();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

运行结果:

IO练习:对文件目录的读取_第1张图片

你可能感兴趣的:(java基础)