I have problem with reading data from file. In each line (except first) first char is lost!
Maybe i have troubles with coding, but i try to set UTF-8, UniCode, ANSI, and result is fast the same...
Code:
try (FileReader fr = new FileReader("123.txt")) {
// create a buffer for file reader
BufferedReader br = new BufferedReader(fr);
do {
input = br.readLine();
System.out.println(input);
} while (br.read() != -1);
} catch (IOException ex) {
System.out.println("IOex : " + ex);
}
Console:
2
FFFFFF
FAF9F5
FDBCA1
FBCCB8
but must be:
2
#FFFFFF
2
#FAF9F5
6
#FDBCA1
9
#FBCCB8
9
it only works, when i put slashes before lines.
2
\#FFFFFF
\2
\#FAF9F5
\6
\#FDBCA1
\9
\#FBCCB8
\9
What can it be?
Thanks!
The problem is with the end of your do
loop:
do {
input = br.readLine();
if (input.endsWith("\n")) {
input = input.substring(0, input.indexOf("\n"));
}
System.out.println(input);
} while (br.read() != -1);
You're calling read()
which will read the first character of the next line - but you're only using that to check for whether the file has ended. (Notice how you've got the first character of the first line, because there you're calling readLine
without previously calling read
.)
This would work fine - and be simpler:
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
readLine
returns null
when you've reached the end of the data. Note that you don't need to check for input
containing \n
as you're already reading one line at a time, and \n
is deemed to be a line separator.
See more on this question at Stackoverflow