【问题标题】:Why does my code not work when I try to merge two (.txt) files into another (.txt) file? [closed]为什么当我尝试将两个 (.text) 文件合并到另一个 (.text) 文件时我的代码不起作用? [关闭]
【发布时间】:2018-02-06 02:34:13
【问题描述】:

我有两个 .txt 文件(file1.txt 和 file2.txt)。在这些文件中有一些字符行。我的意图是将这两个文件的内容合并到另一个文件(file3.txt)中。我的代码如下:

    public static void main(String[] args) {

    try {
        PrintWriter pw = new PrintWriter("file3.txt");
        BufferedReader br1 = new BufferedReader(new FileReader("file1.txt"));
        BufferedReader br2 = new BufferedReader(new FileReader("file2.txt"));


        String line = br1.readLine();
        while(line!=null){
            pw.println(line);
            br1.readLine();
        }

        line = br2.readLine();
        while (line!=null) {
            pw.println(line);
            br2.readLine();

        }

        pw.flush();
        pw.close();

        br1.close();
        br2.close();

    } catch (FileNotFoundException ex) {
        Logger.getLogger(JavaIoProject.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(JavaIoProject.class.getName()).log(Level.SEVERE, null, ex);
    }     
}

编译时没有错误。运行后,当我尝试查看(file3.txt)内部的预期输出时,它没有显示任何内容并且鼠标指针变为处理。为什么会发生这种情况。我忘记添加的缺失部分在哪里,或者我应该编辑哪个部分以及为什么..需要你的帮助..谢谢。

【问题讨论】:

  • 你认为br1.readLine();单独会做什么?
  • 因为你没有把它们加在一起?你只是打开和阅读它们
  • 我认为它返回下一行。不是吗?
  • 那条线你会做什么?
  • 我知道了。。我忘了重新分配。

标签: java bufferedreader printwriter


【解决方案1】:

您在实现中多次重复的大量代码。你可以 只需创建一个方法并根据文件名调用它。

    PrintWriter pw = new PrintWriter("file3.txt");
    readAndWrite(pw, "file1.txt");
    readAndWrite(pw, "file2.txt");

    pw.flush();
    pw.close();

这是 readAndWrite 方法的定义。同时纠正循环。

private static void readAndWrite(PrintWriter pw, String filename) throws FileNotFoundException, IOException {
    BufferedReader br = new BufferedReader(new FileReader(filename));
    String line = br.readLine();
    while (line!=null) {
        pw.println(line);
        line =br.readLine();    
    }
    br.close();
}

【讨论】:

    【解决方案2】:

    你错过了任务。所以你可以试试这样的。

     String line ="";
     while((line=br1.readLine())!=null){
          pw.println(line);
     }
    
     line = "";
     while ((line=br2.readLine())!=null) {
         pw.println(line);
     }
    

    【讨论】:

      【解决方案3】:

      你错过了在循环中重新分配 line 的值,所以你得到一个无限循环。

      更改两个 while 循环:

       while (line!=null) {
              pw.println(line);
              line =br2.readLine();
      
          }
      

      【讨论】:

        猜你喜欢
        • 2022-01-01
        • 2021-02-26
        • 2023-03-29
        • 2014-01-05
        • 1970-01-01
        • 1970-01-01
        • 2015-01-23
        • 1970-01-01
        • 2019-12-29
        相关资源
        最近更新 更多