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!
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With