• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Read text file using delimter "\r\n" only

 
Ajit Kanada
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In my application, I want to read the text file line by line. For this, I used FileReader#readLine() method. But this method uses default delimiter as \n, \r or \r\n.
In the text file, I want to treat the string "\r\n" as new line so that line number is calculated correctly. Individul characters like '\n' or '\r', are not valid line separators in my text file.
Can anybody tell me if I can override the default delimeters so that readLine() method will return the line if it ends with "\r\n" combination only.
If not, is there any other java API which can help me to implement the required functionality?
 
Campbell Ritchie
Sheriff
Pie
Posts: 49804
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By FileReader#readLine, do you mean BufferedReader#readLine? That does not appear to allow a different delimiter. Have you tried the Scanner class, which does allow different delimiters? Is that any use?
Or, use an unbuffered FileReader, put the last character read into a "previousCharacter" local variable and try a while loop
while(!(previousCharacter == '\r' && presentCharacter == '\n')){ . . .}

See whether either of those solutions works.
 
Ajit Kanada
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Scanner is present in JDK 5.0 where as I am using JDK 1.4.2
The second approach to read one character at a time is not efficient.
Can you suggest any other approach?
 
Joe Ess
Bartender
Posts: 9312
10
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use Campbell's algorithm but on a BufferedReader. Efficient and effective.
 
Ajit Kanada
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In worst case, I have to read 60MB of data. I think it will take hell lot of time if I read character by character.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic