Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

unix

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!

like image 477
Monster Avatar asked Jun 18 '09 18:06

Monster


People also ask

How do I print from a PrintWriter?

PrintWriter output = new PrintWriter("output. txt"); To print the formatted text to the file, we have used the printf() method. Here when we run the program, the output.

Is PrintWriter an output stream?

Class PrintWriter. Prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream . It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.

Does PrintWriter create a file?

It's most commonly used for writing data to human readable text files or reports. In our first example, we'll use PrintWriter to create a new file by passing in the filename to its constructor as a string. If the file doesn't exists, it will be created.

Is PrintWriter faster than system out?

PrintWriter class is the implementation of Writer class. By using PrintWriter than using System. out. println is preferred when we have to print a lot of items as PrintWriter is faster than the other to print data to the console.


2 Answers

To write a file with unix line endings, override println in a class derived from PrintWriter, and use print with \n.

PrintWriter out = new PrintWriter("testFile") {
    @Override
    public void println() {
        write('\n');
    }
};
out.println("This file will always have unix line endings");
out.println(41);
out.close();

This avoids having to touch any existing println calls you have in your code.

like image 73
James H. Avatar answered Nov 15 '22 18:11

James H.


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.

like image 35
Jon Skeet Avatar answered Nov 15 '22 20:11

Jon Skeet