Piyush Piyush - 1 year ago 88
Java Question

creating text file and saving in unix format in java

I need to write java code to be able to work in Unix environment for file operations. As I need to deal with files, how do I create and save a file in Unix format in Java?

Answer Source

"Unix format" is simply a text file that denotes line endings with \n instead of \n\r (Windows) or \r (Mac before OSX).

Here's the basic idea; write each line, followed by an explicit \n (rather than .newLine() which is platform-dependent):

public static void writeText(String[] text){
  Path file = Paths.get("/tmp/filename");
  try (BufferedWriter bw = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
    for(String s : text){
  } catch (IOException e) {
    System.err.println("Failed to write to "+file);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download