zoukankan      html  css  js  c++  java
  • 合并多个文件的内容

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

    现在是这样的

    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();
            }
    
        }
        

  • 相关阅读:
    [考试反思]0421省选模拟76:学傻
    [考试反思]0420省选模拟75:安在
    [考试反思]0418省选模拟74:杂枝
    [考试反思]0417省选模拟73:纠结
    [考试反思]0416省选模拟72:停滞
    [考试反思]0415省选模拟71:限制
    [考试反思]0414省选模拟70:阻塞
    [考试反思]0413省选模拟69:遗弃
    [考试反思]0411省选模拟68:毒瘤
    [考试反思]0410省选模拟67:迷惑
  • 原文地址:https://www.cnblogs.com/lonely-buffoon/p/5576280.html
Copyright © 2011-2022 走看看