简体   繁体   中英

while loop is only printing one time instead of for the entire loop

I have a program in which I use a while loop to print both to the console and to a html file. However even though it prints to the console the program will only print the final line to the html file. Here is the code for my loop which is supposed to print the information extracted from a text file for the lines 9 to 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);  
  }

}

EDIT: Through advice posted in answers I now have my output for everything but im having a hard time formatting it the html file has all the lines together with no spacing I tried using "\\n" at the end of my output but then my code doesn't compile because it says a null is not allowed there anyone know how to format this into lines when it wont let me put "\\n" at the end of my print method?

I'm unsure if this is to much code or not enough to solve the problem and if I should add anything to my post or take anything out just let me know.

That's pretty obvious - you create file each time your while loop iterates (see below):

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

You should create your file before entering while loop instead.

So your code should look something like that:

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

---- edit ----

You have updated your code but it's still not ok. You close your file inside of the second loop:

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

When this loop iterates next time you still try to write to your file (and then close it again even though it was closed on previous iteration).

You see only one line in the output file because you are overwriting the file each time you write to it.

If you have to create the PrintWriter within the while(linenum >=9 && linenum <=16) loop, open the file in append mode:

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

will fix your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM