问题
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!
回答1:
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);
}
}
回答2:
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);
}
回答3:
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.
回答4:
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()
回答5:
bufRead.read()
reads the first char.
Do bufRead.ready()
instead.
来源:https://stackoverflow.com/questions/17950908/the-first-character-is-cut-off-when-bufferedreader-is-used