• 合并多个文件的内容


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

    现在是这样的

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

  • 相关阅读:
    三级菜单
    包的初识和进阶&异常处理
    常用模块一
    flask-script
    DBUtils
    Flask-WTForms
    Flask-SQLAchemy
    Flask
    scrapy-redis的使用和解析
    Django的信号;flask的信号;scrapy的信号;
  • 原文地址:https://www.cnblogs.com/lonely-buffoon/p/5576280.html
Copyright © 2020-2023  润新知