Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Detecting linebreaks in files

 
Csaba Kassitzky
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone!

I would like to make a program, which manipulates some files(writing stuff in). For that the best is, if i read characters in instead of lines. Anyone knows how i can detect if my character read in was a linebreak(OS free if possible)?
My codepiece so far:



I need to check ch for being a linebreak or not.
 
Stuart Ash
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you just have to do a System.getProperty("line.separator) for the newline character and check if your ch == this.
 
Alan Moore
Ranch Hand
Posts: 262
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The "line.separator" property just tells you what the operating system thinks is a line break; it doesn't tell you anything about the file you're reading. To detect line breaks in a platform-neutral way, you have to look for '\n', '\r', or the two-character sequence "\r\n".

BTW, there's no need to convert the char to a string to do these tests, just do if (c == '\r') and if (c == '\n').
 
Stuart Ash
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was assuming you the files would have been created on the same OS that the program would be running on. But yes, checking for n and then r and then nr is much better.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does any platform use \r alone? I call \n a new line and ignore \r entirely in one program, but I guess I've only run it on Windows so far.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Stan]: Does any platform use \r alone?

Apple did, up until OS-X. (Now they use \n like other unixes.)

A good article on line separators can be found here.

In Java to detect line breaks I usually just use a BufferedReader. The readLine() method considers "\r\n", "\n", or "\r" as line breaks. Under JDK 5+ you can also use Scanner much the same way.
 
u johansson
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, make sure you do it at the highest abstraction level possible.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic