6

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?

1

2 Answers 2

4

"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){
      bw.write(s);
      bw.write("\n");
    }
  } catch (IOException e) {
    System.err.println("Failed to write to "+file);
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Instead of using \n or \r\n, use System.getProperty("line.separator").
Thanks dimo414 and Eng.Fouad. The above example helped a lot.
@Eng.Fouad Generally speaking, true, but if you want a Unix-format file no matter what OS you're on, you'll want to use \n explicitly. Getting the system's line separator means you'll get different behavior depending on the OS you run the program on.
1

Oracle has good documentation on that:

http://docs.oracle.com/javase/tutorial/essential/io/file.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.