File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Detecting linebreaks in files Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Detecting linebreaks in files" Watch "Detecting linebreaks in files" New topic

Detecting linebreaks in files

Csaba Kassitzky
Ranch Hand

Joined: Nov 29, 2005
Posts: 38
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

Joined: Oct 07, 2005
Posts: 637
I think you just have to do a System.getProperty("line.separator) for the newline character and check if your ch == this.

ASCII silly question, Get a silly ANSI.
Alan Moore
Ranch Hand

Joined: May 06, 2004
Posts: 262
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

Joined: Oct 07, 2005
Posts: 637
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

Joined: Jan 29, 2003
Posts: 8791
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.

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
[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.

"I'm not back." - Bill Harding, Twister
u johansson
Ranch Hand

Joined: Dec 27, 2005
Posts: 47
Well, make sure you do it at the highest abstraction level possible.
I agree. Here's the link:
subject: Detecting linebreaks in files
It's not a secret anymore!