This is the code :
File file = new File("Hello.txt");
file.createNewFile();
FileWriter write = new FileWriter(file);
BufferedWriter bufWrite = new BufferedWriter(write);
bufWrite.write("HelloWorld");
bufWrite.flush();
bufWrite.close();
FileReader read = new FileReader(file);
BufferedReader bufRead = new BufferedReader(read);
while(bufRead.read()!=-1){
System.out.println(bufRead.readLine());
}
bufRead.close();
Here, the output is elloWorld. 'H'is not there. Why is it so? Not sure if I'm doing anything wrong here!
Class BufferedReader. Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used.
maybe it was other way for some years, or will be other way in future, but now it is stricctly specified to 8192 in the java.
Initializing a BufferedReader. Wrapping the FileReader like this is a nice way to add buffering as an aspect to other readers. This will set the buffer size to 16384 bytes (16 KB). The optimal buffer size depends on factors like the type of the input stream and the hardware on which the code is running.
Closes this stream and releases any system resources associated with it. If the stream is already closed then invoking this method has no effect. So, if you don't close(), system resources may be still associated with the reader which may cause memory leak.
It's a surprising common question.
When you do
bufRead.read()
you actually read a character, it doesn't put it back and let you read it again later.
The simplest solution is to not do this.
File file = new File("Hello.txt");
try (PrintWriter pw = new PrintWriter(new FileWriter(file))) {
pw.println("HelloWorld"); // should have a new line
}
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
for (String line; (line = br.readLine()) != null; ) {
System.out.println(line);
}
}
Look at your loop:
while(bufRead.read()!=-1){
System.out.println(bufRead.readLine());
}
You're using read
in the loop - which will consume the first character of the next line.
You should use:
String line;
while ((line = bufRead.readLine()) != null) {
System.out.println(line);
}
That has a very simple reason: The line
while(bufRead.read()!=-1){
consumes one character from the input stream. From the documentation:
Reads a single character. This method will block until a character is available, an I/O error occurs, or the end of the stream is reached.
You already read a character at
while(bufRead.read()!=-1)
If there are more than one lines then it will vanish first character of every line!
so use
String line;
while ((line = bufRead.readLine()) != null) {
System.out.println(line);
}
See read() readLine()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With