A Funny Java Flavoured Look at the World

Thursday, October 05, 2006

\n - newline saves the day and formats all my troubles away

I had an interesting problem today. I was reading in a file line by line and when a certain line came in I was catching it and replacing the line with a changed version. The problem I then had was when I was writing the file back out, the code supplied by the excellent Java Almanac helped with this

The java.io stuff is really easy to use and saved me loads of time recently. Actually looking at the Almanac I could have used a regular expression on the file, it may be quicker that way but I already had the code to read in files and change them so I went with what I knew.

Anyway so I was reading in the file, doing a switch on some of the values and then writing the String to a file. The problem I was having was that it just came out as one great big long line and I wasn't sure how to format it. As people who read in Strings and make them into File's will know you have to double up on the backslashes. Recently when studying for my Java exam they make you learn a small amount of Regular expression stuff and the reason you have to double up on the back slashes is because regular expressions have a lot of constructs which use a backslash and then a letter or number to mean something else. These special \ enabled regular expression values I think are called meta-characters. You can find more about the Regular-expression constructs here

So why am I talking about this it's because what I needed to add to the end of each line when I read it in was a \n which a character literal for newline. I added this baby in and boom the whole document was formatted again. Below is what I added

\n The newline (line feed) character ('\u000A')

once again the fuzzy knowledge learnt by studying for the SCJP exam has come to help me out.

1 Comments:

  • Take a look at commons-io - http://jakarta.apache.org/commons/io/ - in particular the FileUtils class.

    You can do:
    List lines = FileUtils.readLines(file);
    // process the lines
    FileUtils.writeLines(file, lines);

    or use the lineIterator to iterate through each line. Its much simpler and more reliable than doing it manually.

    By Anonymous Stephen Colebourne, at Thu Oct 05, 12:34:00 pm 2006  

Post a Comment

Links to this post:

Create a Link

<< Home