简体   繁体   中英

Reading and writing text is not complete?

There seems to be a problem with reading and writing from a textfile.

While having two different files I printed out the content and it doesn't seem the same as it should be in the textfiles.

I tried to add + and without, and to add bw.close() or without. I tried also to use scanner instead, but it didn't print out anything.

Could it be changed somehow ?

  private void readFromFile(File cf2) throws IOException, Exception {

   FileReader fr = new FileReader(cf2);
   try (BufferedReader bw = new BufferedReader(fr)) {
    System.out.println("Wait while reading !");

    while(bw.readLine() != null)
    s1 += bw.readLine();
    System.out.println(s1);
    bw.close();
   } System.out.println("File read !");
  }

You are using bw.readLine() twice, witch consumes two lines, but you are adding only one of them to s1 each time. Try

String line;
while((line = bw.readLine()) != null)
    s1 += line;
System.out.println(s1);

Half of your readLine calls are used for checking the data for null , the other half get added to s1 . That's why you get only part of the input.

To fix your code, make a loop like this:

while (true) {
    String s = bw.readLine();
    if (s == null) break;
    s1 += s;
}

However, this is grossly inefficient. You would be better off using StringBuffer :

StringBuffer sb = new StringBuffer()
while (true) {
    String s = bw.readLine();
    if (s == null) break;
    sb.append(s);
    // Uncomment the next line to add separators between lines
    // sb.append('\n');
}
s1 = sb.toString();

Note that none of '\\n' symbols from your file would be in the output string. To add separators back, uncomment the commented line in the code above.

You call readline() twice, so you only get every second line.

  private void readFromFile(File cf2) throws IOException, Exception {

   FileReader fr = new FileReader(cf2);
   try (BufferedReader br = new BufferedReader(fr)) {
       System.out.println("Wait while reading !");
       StringBuilder sb = new StringBuilder();
       String s;
       while((s = br.readLine()) != null) {
           sb.append(s);
       }
       System.out.println(sb.toString());
   }
  System.out.println("File read !");
  }

You don't need to close br because that is done by try-with-resources.

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