Is there a way to make PrintWriter output to UNIX format?

java, unix

Solution

Note: as reported in comments, the approach given below breaks in JDK 9+. Use the approach in James H.'s answer.

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.

Problem

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!

Original source