Search code examples
javacharbufferedreader

How to resolve BufferedReader() with blanks?


Got a problem. Why are the blanks in both opt cases? (By using readLine() it's no problem.)

Thanks!

 String srcFile = "d:/javatest/File2String.txt";

 BufferedReader br = new BufferedReader(new FileReader(srcFile));

 char[] chs = new char[1024];

 int len = 0;

 //opt 1    while ((len = br.read(chs, 0, len)) != -1){   // Why are blanks with no endings???

 //opt 2    while ((len = br.read(chs)) != -1){           // Why are blanks with length of len???

 System.out.println(chs);

 }

Solution

  • The line System.out.println(chs); always prints 1024 characters regardless of how many characters were read into chs. In opt2 you read len characters, and print 1024 characters so there will be extra characters in the output when len < 1024 - these are \0 for small file, or will repeat the value read by the previous iteration for the final loop when filesize > 1024.

    In opt1 len is zero initially so you are calling br.read(chs, 0, 0) in an infinite loop. You ask to read 0 and get 0 back - len never changes from 0 as each read returns 0 and assigns back to len. Each time you print 1024 values of chs - all set to \0.

    You could print the exact chs buffer content each time by looping i= 0 to len and print System.out.print(chs[i]), or in one step with System.out.println(new String(chs, 0, len)) but note that this is duplicating / copying the contents again.

    If you simply want to cat/type the file to current console you can do it without BufferedReader with:

    try(var os = new FileInputStream(srcFile)) {
       os.transferTo(System.out);
    }