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

前端 未结 5 437
梦谈多话
梦谈多话 2020-12-11 16:46

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!

5条回答
  •  天命终不由人
    2020-12-11 17:14

    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.

提交回复
热议问题