Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Help with File Output Formatting  RSS feed

 
Eugene Armistead
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
This may be kind of a beginner question, but please bear with me.
I am working in Windows and am writing an application that takes a configuration file written by another program, lets the user modify the configurations, and then writes the file back out in the same format as the original.
My problem is that I can't get the output to look right. When I view the file in NOTEPAD, it looks something like:
LINE ONE INFORMATION
LINE TWO INFORMATION
LINE THREE INFORMATION
and so on. When I write it back out, I get:
LINE ONE INFORMATION<\N>LINE TWO INFORMATION<\N>LINE THREE INFORMATION<\N>
and so on, where '<\N>' is the control character for new line.
When I look at my file in NOTEPAD, I get results as mentioned above. If I use a more advanced editor like TEXPAD, which can recognize the new line character, my file looks fine and is indistinguishable from the original. The problem is that the program that uses this config file parses by line and has trouble reading my output file.
I have tried using FileOutputStream and FileWriter API's. I have tried sending Char Arrays, String Arrays and straight Strings. Writing output a line at a time, writing with the whole thing as one String with '\n' in the proper places - all with no luck. What would be a proper way to get each line formatted correctly?
 
Kathy Rogers
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try using a BufferedWriter to wrap the FileWriter (by using a constructor like this:- new BufferedWriter(new FileWriter(outFile)) ). BufferedWriter has a newLine method() which you can use instead of \n.
Hope this helps,
Kathy
 
Steve Deadsea
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Line ending characters vary across platforms. Luckily the line ending that applications on a system expect is a System property.
Your code should look something like this:
out.write("Line one");
out.write(System.getProperty("line.separator));
out.write("Line two");
out.write(System.getProperty("line.separator"));
out.write("Line three");
out.write(System.getProperty("line.separator"));
btw, the Windows line separator is "\r\n".
 
Eugene Armistead
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Kathy/Steve,
Kathy's method worked perfectly.
Thank you both for your help!
regards,
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!