Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading text file, skips 1st character of next line

Status
Not open for further replies.

feltell

Programmer
Mar 26, 2004
1
GB
I'm reading a text file into my program using a FileReader. I am attempting to get it to skip past newlines, \n and \r. When it skips a \r however it seems to skip the character after it as well, so the first character on every line is missing. If I println the skipped character (should be just a carriage return) it prints not only the carriage return but the first character of the next line as well:
Code:
int nextChar;
nextChar = fr.read();
...
while ((char)nextChar == '\n')
	// || (char)nextChar == '\r')  	
	nextChar = fr.read();

if (	(char)nextChar == '1' 
	|| (char)nextChar == '0'){
	...
}else{
	System.out.print("\nERROR: INVALID CHARACTER = " + (char)nextChar);
}
The above (notice the commmented out \r bit) outputs not only a newline after the "ERROR", but the first character of the next line as well. If I uncomment the \r section of the while-loop it skips the first character as well as the carriage return.
I cant really see how this is possible and its really getting on my nerves. Any help would be much appreciated.

Dave.
 
I don't see the error, but the code shown will not read more than one line - perhaps it's in the surrounding code?

Perhaps it would be practical, to use BufferedReader.readLine () as Wrapper around FileReader?
This class allows reading of whole lines (and throws away EOLs). And it works with different concepts of EOL (Mac, Linux, Dos).
 
the code that you've shown only loop through one character except \r\n. Looks like you have another outer loop to your code. I suspect that problem is

Code:
int nextChar;
nextChar = fr.read();  [COLOR=red]<-- always read one more character
                           in addition to this[/color]
                                               [COLOR=red]|[/color red]
while ((char)nextChar == '\n')                 [COLOR=red]|[/color red]
    // || (char)nextChar == '\r')              [COLOR=red]|[/color red]
    nextChar = fr.read();    [COLOR=red]<-----------------[/color]

if (    (char)nextChar == '1' 
    || (char)nextChar == '0'){
    ...
}else{
    System.out.print("\nERROR: INVALID CHARACTER = " + (char)nextChar);
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top