• 合并多个文件的内容


    合并的结果应该是这样的:

    现在是这样的

    public static void main(String[] args) {
            List<Object> list = new ArrayList<>();
            File file1 = new File("d:\ti.txt");
            File file2 = new File("d:\titi.txt");
            list.add(file1);
            list.add(file2);
            FileWriter writer = null;
            BufferedReader reader = null;
            try {
                for (int i = 0; i < list.size(); i++) {
                    File f = (File) list.get(i);
                    writer = new FileWriter("d:\concatenation.txt");
                    reader = new BufferedReader(new FileReader(f));
                    
                    String l;
                    while ((l = reader.readLine()) != null) {
                        writer.write(l);
                    }
                }
            writer.flush();
            writer.close();
            reader.close();
            
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
        

    运行,得到结果如下

    怎么只有第二个文件的内容?

    原来这一句writer = new FileWriter("d:\concatenation.txt");写在循环里了,因为writer是引用,所以writer是先指向了一个new FileWriter("d:\concatenation.txt")地址,循环一下,又指向了一个新的new FileWriter("d:\concatenation.txt")地址,这时文件只有文件二了,所以写入的只有文件二的内容了

    总的目标是一个,所以要写在循环外

    public static void main(String[] args) {
            List<Object> list = new ArrayList<>();
            File file1 = new File("d:\ti.txt");
            File file2 = new File("d:\titi.txt");
            list.add(file1);
            list.add(file2);
            FileWriter writer = null;
            BufferedReader reader = null;
            try {
                writer = new FileWriter("d:\concatenation.txt");
                for (int i = 0; i < list.size(); i++) {
                    File f = (File) list.get(i);
                    reader = new BufferedReader(new FileReader(f));
                    String l;
                    while ((l = reader.readLine()) != null) {
                        writer.write(l);
                    }
                }
            writer.flush();
            writer.close();
            reader.close();
            
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
        

  • 相关阅读:
    Ajax实践学习笔记(三) Ajax应用模型
    代码之美
    Git 和Github初次使用 (转) Anny
    VisitsPageViewUnique Visitors: Metrics From GA Anny
    Building and Installing Node.js Anny
    Callback in NodeJS Anny
    Intall Apache & php on Ubuntu Anny
    [转载]Linux系统下超强远程同步备份工具Rsync使用详解 Anny
    Cannot Boot WEBrick: "WARN TCPServer Error: Address already in use " Anny
    chmod(转) Anny
  • 原文地址:https://www.cnblogs.com/lonely-buffoon/p/5576280.html
Copyright © 2020-2023  润新知