美文网首页Java学习
Java 读写文本文件

Java 读写文本文件

作者: xiaogp | 来源:发表于2020-07-16 17:38 被阅读0次

    读取txt
    File
    FileInputStream
    InputStreamReader
    BufferedReader

    写入txt
    File
    FileWriter
    BufferedWriter

    package main;
    
    import java.io.*;
    import java.util.*;
    import java.util.stream.Collectors;
    
    public class ReadSaveFileTest {
        public static void main(String[] args) {
            // 追加写入List元素到本地文件
            saveTxt();
    
            // 读取本地txt文件为一个String
            String res = readTxt("/home/save.txt");
            System.out.println(res);
            System.out.println("=======================");
    
            // 读取本地txt文件, 每行是一个List的元素
            List<String> text = readText3();
            System.out.println(text);
            List<String> name = text.stream().map(x -> x.split(",")[0]).collect(Collectors.toList());
            List<Double> score = text.stream().map(x -> Double.valueOf(x.split(",")[1])).collect(Collectors.toList());
            System.out.println(name);
            System.out.println(score);
    
            System.out.println("======================");
            // 读取本地txt文件, 每一列为一个list
            Map<String, Object> bbb = readTxt2();
            List<String> aColumn = (List<String>) bbb.get("a");
            List<Double> bColumn = (List<Double>) bbb.get("b");
            System.out.println(aColumn);
            System.out.println(bColumn);
    
            // 读取本地文件为一个字典
            System.out.println("========================");
            Map<String, Double> ccc = readTxt4();
            System.out.println(ccc);
            System.out.println(ccc.get("21466"));
        }
    
    
        public static Map<String, Object> readTxt2() {
            Map<String, Object> result = new HashMap<>();
            List<String> a = new ArrayList<>();
            List<Double> b = new ArrayList<>();
            File file = new File("/home/save.txt");
            if (file.isFile() && file.exists()) {
                try {
                    FileInputStream fileInputStream = new FileInputStream(file);
                    InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    String text = null;
                    while ((text = bufferedReader.readLine()) != null) {
                        String[] splitLine = text.split(",");
                        if (splitLine.length == 2) {
                            String name = splitLine[0];
                            double score = Double.valueOf(splitLine[1]);
                            a.add(name);
                            b.add(score);
                        }
                    }
                    result.put("a", a);
                    result.put("b", b);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return result;
        }
    
        public static List<String> readText3() {
            List<String> result = new ArrayList<>();
            File file = new File("/home/save.txt");
            if (file.isFile() && file.exists()) {
                try {
                    // 字节流
                    FileInputStream fileInputStream = new FileInputStream(file);
                    // 字符流
                    InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
                    // 缓冲
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    String text = null;
                    while ((text = bufferedReader.readLine()) != null) {
                        if (text.split(",").length == 2) {
                            result.add(text);
                        }
                    }
                    return result;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return result;
        }
    
        public static Map<String, Double> readTxt4() {
            Map<String, Double> result = new HashMap<>();
            File file = new File("/home/save.txt");
            if (file.isFile() && file.exists()) {
                try {
                    FileInputStream fileInputStream = new FileInputStream(file);
                    InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    String text = null;
                    while ((text = bufferedReader.readLine()) != null) {
                        String[] textSplit = text.split(",");
                        if (textSplit.length == 2) {
                            String name = textSplit[0];
                            double score = Double.valueOf(textSplit[1]);
                            result.put(name, score);
                        }
                    }
                    return result;
                } catch (Exception p) {
                    p.printStackTrace();
                }
            }
            return result;
        }
    
    
        public static String readTxt(String txtPath) {
            File file = new File(txtPath);
            if (file.isFile() && file.exists()) {
                try {
                    // FileInputStream: 字节流, 对文件数据以字节的形式进行读取操作
                    // 根据File对象代表的文件路径建立链接创建FileInputStream对象
                    FileInputStream fileInputStream = new FileInputStream(file);
                    // InputStreamReader, 字符流, 类是从字节流到字符流的桥接器:它使用指定的字符集读取字节并将它们解码为字符
                    // 字节解码成字符需要的字节个数不同
                    // 那么就需要一个流把字节流读取的字节进行缓冲而后在通过字符集解码成字符返回,因而形式上看是字符流
                    InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
                    // BufferedReader类从字符输入流中读取文本并缓冲字符,以便有效地读取字符,数组和行
                    // 为了提高字符流读写的效率,引入了缓冲机制,进行字符批量的读写,提高了单个字符读写的效率。BufferedReader用于加快读取字符的速度
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    
                    StringBuilder sb = new StringBuilder();
                    String text = null;
                    while ((text = bufferedReader.readLine()) != null) {
                        sb.append(text);
                    }
                    return sb.toString();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    
        /**
         * 覆盖写入, 不需要提前创建文件
         */
        public static void saveTxt() {
            try {
                File file = new File("/home/save.txt");
                // BufferedWriter用于加快写入的速度
                // FileWriter第二个参数指定true是追加模式, 默认是false
                BufferedWriter out = new BufferedWriter(new FileWriter(file, true));
    
                List<String> name = Arrays.asList("10313", "23424", "21466");
                List<Double> score = Arrays.asList(0.3, 0.4, 0.5);
                for (int i = 0; i < name.size(); i++) {
                    out.write(name.get(i) + "," + score.get(i) + "\n");
                }
                out.flush(); // 把缓存区内容压入文件
                out.close(); // 最后记得关闭文件
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    

    相关文章

      网友评论

        本文标题:Java 读写文本文件

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