tags:

views:

303

answers:

2

In Java, of course. I'm writing a program and running it under a Windows environment, but I need the output (.csv) to be done in Unix format. Any easy solution? Thanks!

+3  A: 

By "Unix format" do you mean using "\n" as the line terminator instead of "\r\n"? Just set the line.separator system property before you create the PrintWriter.

Just as a demo:

import java.io.*;

public class Test
{
    public static void main(String[] args)
        throws Exception // Just for simplicity
    {
        System.setProperty("line.separator", "xxx");
        PrintWriter pw = new PrintWriter(System.out);
        pw.println("foo");
        pw.println("bar");
        pw.flush();
    }
}

Of course that sets it for the whole JVM, which isn't ideal, but it may be all you happen to need.

Jon Skeet
Excellent, thanks!
Monster
+2  A: 

Assuming the formatting issue you refer to is that Windows line breaks are Carriage Return-Line Feed ("\r\n") while Unix ones are Line Feed ("\n") only, the easiest way to make sure your file uses LF and not CRLF is to eschew println and instead use print("\n") to terminate lines.

So instead of:

writer.println("foo,bar,88");

use

writer.print("foo,bar,88\n");

You can just search the relevant files for println to make sure you catch them all.

Zarkonnen
The difference between this approach and Jon Skeet's is that his is global, but requires fewer changes. As long as you're sure you don't care that everything in your program will be using \n instead or \r\n, just setting line.separator is probably easier.
Zarkonnen
Ah, I see. Excellent idea also. In my case though (although I should have specified), I'm looking for a global approach. Thanks!
Monster