Creating a text file and saving in unix format in java

I need to write Java code to work in a Unix environment for file operations. How do I need to process files, how do I create and save a file in Unix format in Java?

+6
source share
2 answers

"Unix format" is just a text file that marks the end of lines with \n instead of \n\r (Windows) or \r (Mac before OSX).

Here is the basic idea; write each line followed by an explicit \n (and not .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); } } 
+4
source

Oracle has some good documentation about this:

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

+1
source

Source: https://habr.com/ru/post/920746/


All Articles