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

  • 相关阅读:
    对cross-env的理解
    【好好学习】mh_h5
    QS工具入门
    vue中用qs传参发送axios请求
    Web API 异常处理
    WEB API Filter的使用以及执行顺序
    RSA/SHA1加密和数字签名算法在开放平台中的应用
    windows上RSA密钥生成和使用
    Cordova Error: cmd: Command failed with exit code ENOENT
    Cordova热更新cordova-hot-code-push
  • 原文地址:https://www.cnblogs.com/lonely-buffoon/p/5576280.html
Copyright © 2011-2022 走看看