Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating text file and saving in unix format in java

Tags:

java

unix

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?

like image 832
Piyush Avatar asked Jul 17 '12 21:07

Piyush


People also ask

How do I save a file in Unix format?

To write your file in this way, while you have the file open, go to the Edit menu, select the "EOL Conversion" submenu, and from the options that come up select "UNIX/OSX Format". The next time you save the file, its line endings will, all going well, be saved with UNIX-style line endings.

Is .Java a text file?

All java files are text files, but not all text files are java files.


1 Answers

"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);
  }
}
like image 159
dimo414 Avatar answered Oct 20 '22 01:10

dimo414