【问题标题】:while loop is only printing one time instead of for the entire loopwhile 循环只打印一次而不是整个循环
【发布时间】:2013-04-21 09:05:04
【问题描述】:

我有一个程序,我在其中使用 while 循环来打印到控制台和 html 文件。然而,即使它打印到控制台,程序也只会将最后一行打印到 html 文件。这是我的循环的代码,它应该打印从文本文件中提取的第 9 到 16 行的信息。

  //read the txt file
Path objPath = Paths.get("dirsize.txt");  
if (Files.exists(objPath))
{

    File objFile = objPath.toFile();
  try(BufferedReader in = new BufferedReader(
                          new FileReader(objFile)))
   {
    String line = in.readLine();
    int lineNum = 1;
    //extract the month
    String monthSubstring = line.substring(25,27);
    month = Integer.parseInt(monthSubstring) -1 ;
    //extact the year
    String yearSubstring = line.substring(31,35);
    year = (Integer.parseInt(yearSubstring));
    //extract the date
    String daySubstring = line.substring(28,30);
    day = Integer.parseInt(daySubstring);
     PrintWriter out = new PrintWriter (new BufferedWriter(new FileWriter("Output.html")));
    while(line != null)
    {
      line = in.readLine();
      lineNum ++;
      if (lineNum == 3)
       {
           //extract the hour
            String hourSubstring = line.substring(21,23);
             hour = Integer.parseInt(hourSubstring); 
            //extract the minute
            String minuteSubstring = line.substring(24,26);
             minute = Integer.parseInt(minuteSubstring);
            //extract the second
            String secondSubstring = line.substring(27,29);
            second= Integer.parseInt(secondSubstring);
           }
      if(lineNum ==5)
       {
            //Extract the branch
            strBranch = line.substring(22, 27);        
       }        
      if (lineNum == 6)
      {
             //Extract the computer
             strCPU = line.substring(26,32);
      }   
     if (lineNum >= 9 && lineNum <= 16)
      {
          //call the MyDirectory methods to get the files name,size and number of files
          MyDirectory directory = new MyDirectory(line);
          fileName = directory.getName();
          fileSize = directory.getsize();
          fileNum = directory.getNum();
          //create the dteDate calender
          GregorianCalendar dteDate = new GregorianCalendar(year, month, day, hour, minute, second);
          //fromat the date
          SimpleDateFormat strDate = new SimpleDateFormat("MMM dd, yyyy h:m");
        //Write the data to the file
         out.println((strBranch + "; " +
                  strCPU + "; "  + 
                  strDate.format(dteDate.getTime())) + "; " +
                  fileName + "; " +
                  fileSize + "; " + 
                  fileNum);
         //create the necessary output for the console
          System.out.println((strBranch + "; " +
                  strCPU + "; "  + 
                  strDate.format(dteDate.getTime())) + "; " +
                  fileName + "; " +
                  fileSize + "; " + 
                  fileNum);
        }    
       out.flush();
    }

   }   

  //catch any IOExceptions and print out e
 catch (IOException e)
  {
    System.out.println(e);  
  }

}

编辑:通过答案中发布的建议,我现在有了所有内容的输出,但我很难对其进行格式化,html 文件包含所有行,没有空格我尝试在输出末尾使用“\n”但是那么我的代码无法编译,因为它说不允许 null 有谁知道如何将其格式化为行,因为它不允许我在打印方法的末尾放置“\n”?

我不确定这是代码太多还是不足以解决问题,如果我应该在帖子中添加任何内容或删除任何内容,请告诉我。

【问题讨论】:

    标签: java printing while-loop


    【解决方案1】:

    这很明显 - 每次 while 循环迭代时都会创建文件(见下文):

                 PrintWriter out = new PrintWriter (
                               new BufferedWriter(
                               new FileWriter("Output.html")));
            //Write the data to the file
             out.println((strBranch + "; " +
                      strCPU + "; "  + 
                      strDate.format(dteDate.getTime())) + "; " +
                      fileName + "; " +
                      fileSize + "; " + 
                      fileNum);
            //flush the data and close the output stream
             out.close();
    

    您应该在进入 while 循环之前创建文件。

    所以你的代码应该是这样的:

         PrintWriter out = new PrintWriter (new BufferedWriter(new FileWriter("Output.html")));
         while(line != null)
        {
            //perform your file operations here
        }
        out.close();
    

    ----编辑----

    您已经更新了代码,但仍然不行。在第二个循环中关闭文件:

            (...)
     while (lineNum >= 9 && lineNum <= 16)
      {
          //call the MyDirectory methods to get the files name,size and number of files
          MyDirectory directory = new MyDirectory(line);
          fileName = directory.getName();
          fileSize = directory.getsize();
          fileNum = directory.getNum();
          //create the dteDate calender
          GregorianCalendar dteDate = new GregorianCalendar(year, month, day, hour, minute, second);
          //fromat the date
          SimpleDateFormat strDate = new SimpleDateFormat("MMM dd, yyyy h:m");
        //Write the data to the file
         out.println((strBranch + "; " +
                  strCPU + "; "  + 
                  strDate.format(dteDate.getTime())) + "; " +
                  fileName + "; " +
                  fileSize + "; " + 
                  fileNum);
        //flush the data and close the output stream
         //################# YOU CLOSE YOUR FILE HERE:
         out.close();
         //create the necessary output for the console
          System.out.println((strBranch + "; " +
                  strCPU + "; "  + 
                  strDate.format(dteDate.getTime())) + "; " +
                  fileName + "; " +
                  fileSize + "; " + 
                  fileNum);
         //move on in the loop so it's not infinte
          break;
       }    
    }
    

    当此循环下次迭代时,您仍会尝试写入文件(然后再次关闭它,即使它在上一次迭代中已关闭)。

    【讨论】:

    • 也许我实现了这个错误,但它没有解决我的问题我将我的代码更新到我的原始帖子中,这样你就可以看到我是如何做到的
    • 嗯,现在我在 html 文件中什么都没有得到它完全是空的,我编辑我的代码以显示我更改了哪些部分,因为我可能做错了
    • 我将关闭操作移到第二个 } 之后,然后循环结束,但现在我的 html 文件是空的,并且没有从我的打印方法接收任何数据
    • 当我没有 break 语句时,它会永远打印出第一行
    【解决方案2】:

    您在输出文件中只看到一行,因为每次写入文件时都会覆盖该文件。

    如果您必须在 while(linenum >=9 && linenum

    new FileWriter("Output.html", true);

    会解决你的问题。

    【讨论】:

    • 这确实解决了并非所有内容都写入文件的问题,但会产生文件上的所有内容都在一起而不是新行的问题。我尝试在 out.println(Printed stuff here) 末尾使用“\n”修复此问题,但随后出现错误,即不允许使用 void 类型
    • 实际上,您不需要在 BufferedWriter 周围包装 PrintWriter,仅 BufferedWriter 就可以在您的情况下工作。只需在 BufferedWriter 对象上调用 write() 方法,然后调用 newLine() 方法。那应该可以解决它。
    • 我将构造函数更改为 BufferedWriter out = new BufferedWriter ((new FileWriter("Output.html")));但是现在程序找不到 out.println 的 println 方法
    • BufferedWriter 类没有 println() 方法。正如我在评论中提到的,您应该使用 write() 方法将内容写入文件,然后调用 BufferedWriter 对象上的 newLine() 方法以确保所有内容都不会写入同一行。如果它解决了您的问题,也请将我的原始回复标记为正确答案。
    猜你喜欢
    • 2015-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-21
    相关资源
    最近更新 更多