You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java读取两个文本文件写入同一文件异常:仅写入单个文件的解决方法

问题:合并两个文件内容时仅写入了其中一个文件的内容

我写了一个基础练习程序,目的是读取even.txt和old.txt两个文本文件的内容,然后把所有内容写入both.txt,要求both.txt包含这两个文件的全部内容。但运行代码后发现,both.txt里只有old.txt的内容,even.txt的内容完全没写进去,请问该怎么解决?

我的代码如下:

package files;
import java.io.*;
import java.util.*;

public class Files {

    public static void main(String[] args) throws IOException {
        
    Scanner thoko = new Scanner(System.in);
    System.out.println("Choose the file you want to write to:");
        
    int number = thoko.nextInt();
    switch (number){
        case 1:
            try{
                File even = new File("even.txt");
                even.createNewFile();

                PrintWriter write = new PrintWriter(new FileWriter("even.txt"));

                for (int i=1; i<=10; i++){
                    if(i%2==0){
                        write.print(i+",");
                    }
                }
                System.out.println("Writting to an even text file is a succes");
                write.close();
                
                
            }
            
            catch (FileNotFoundException e){
                    System.out.println("Error opening the file even.txt");
                    System.exit(0);
                }   break;
                
        case 2:
            try{
                File old = new File("old.txt");
                old.createNewFile();

                PrintWriter write = new PrintWriter(new FileWriter("old.txt"));

                for (int i=1; i<=10; i++){
                    if(i%2==1){
                        write.print(i+",");
                    }
                }
                System.out.println("Writting to an old text file is a succes");
                write.close();
                

            }
            
            catch (FileNotFoundException e){
                    System.out.println("Error opening the file old.txt");
                    System.exit(0);
                }   break;
                
        case 3:
            try{
                FileReader me = new FileReader("even.txt");
                FileReader ne = new FileReader("old.txt");
                
                FileWriter de = new FileWriter("both.txt");
                
                String str = "";
                int i;
                
                while ((i = me.read())!=-1 && (i = ne.read())!=-1){
                    str +=(char)i;
                }
                System.out.println("Writting to both file done");
                de.write(str);
                
                
                me.close();
                ne.close();
                de.close();
                }
            catch (FileNotFoundException e){
                    System.out.println("Error opening the file old.txt");
                    System.exit(0);
                }   break;
            }
            
            }
            
    } 

问题原因

问题出在case 3的循环逻辑上:

  • 你的while循环条件是(i = me.read())!=-1 && (i = ne.read())!=-1,每次循环会先读取even.txt的一个字符,但紧接着就会读取old.txt的一个字符覆盖变量i的值,所以最终str里只会添加old.txt的字符。
  • 同时,&&逻辑意味着只要其中一个文件读取完毕(返回-1),循环就会立即停止,另一个文件剩下的内容也不会被读取。

解决方法

需要分开读取两个文件的内容,先读完第一个文件的所有内容,再读第二个文件的所有内容,然后依次写入both.txt。修改后的case 3代码如下:

case 3:
    try{
        FileReader evenReader = new FileReader("even.txt");
        FileReader oldReader = new FileReader("old.txt");
        FileWriter bothWriter = new FileWriter("both.txt");

        int c;
        // 先读取even.txt的全部内容并写入
        while ((c = evenReader.read()) != -1) {
            bothWriter.write(c);
        }
        // 再读取old.txt的全部内容并写入
        while ((c = oldReader.read()) != -1) {
            bothWriter.write(c);
        }

        System.out.println("写入both文件完成");
        evenReader.close();
        oldReader.close();
        bothWriter.close();
    } catch (FileNotFoundException e){
        System.out.println("打开文件even.txt或old.txt出错");
        System.exit(0);
    } catch (IOException e) {
        System.out.println("读写文件时发生错误");
        System.exit(0);
    }
    break;

额外优化建议

  1. 使用try-with-resources自动关闭资源:Java 7及以上版本支持这种语法,无需手动调用close(),避免因忘记关闭导致的资源泄漏:
case 3:
    try (FileReader evenReader = new FileReader("even.txt");
         FileReader oldReader = new FileReader("old.txt");
         FileWriter bothWriter = new FileWriter("both.txt")) {

        int c;
        while ((c = evenReader.read()) != -1) {
            bothWriter.write(c);
        }
        while ((c = oldReader.read()) != -1) {
            bothWriter.write(c);
        }

        System.out.println("写入both文件完成");
    } catch (FileNotFoundException e){
        System.out.println("打开文件even.txt或old.txt出错");
        System.exit(0);
    } catch (IOException e) {
        System.out.println("读写文件时发生错误");
        System.exit(0);
    }
    break;
  1. 使用BufferedReader提高读取效率:对于较大的文件,缓冲流能显著提升读写速度:
case 3:
    try (BufferedReader evenReader = new BufferedReader(new FileReader("even.txt"));
         BufferedReader oldReader = new BufferedReader(new FileReader("old.txt"));
         BufferedWriter bothWriter = new BufferedWriter(new FileWriter("both.txt"))) {

        String line;
        // 按行读取even.txt并写入
        while ((line = evenReader.readLine()) != null) {
            bothWriter.write(line);
            bothWriter.newLine(); // 保留换行符
        }
        // 按行读取old.txt并写入
        while ((line = oldReader.readLine()) != null) {
            bothWriter.write(line);
            bothWriter.newLine();
        }

        System.out.println("写入both文件完成");
    } catch (FileNotFoundException e){
        System.out.println("打开文件even.txt或old.txt出错");
        System.exit(0);
    } catch (IOException e) {
        System.out.println("读写文件时发生错误");
        System.exit(0);
    }
    break;

内容的提问来源于stack exchange,提问作者thattCharles

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 14:24:18