3

I'm trying to programically create a new a file in java, and write a string array to that file. If the file already exists, I just want to append another string array (This is like a log file). Whats the most 'modern' way to do something like this? Is FileWriter and Buffered writer still the way to go? Most of the stuff I'm finding on here is from 2010..that was 5 years ago!

Edit: I actually need to take in an ArrayList but there shouldnt be a difference

stepheaw
  • 1,683
  • 3
  • 22
  • 35

4 Answers4

5

Using Java NIO, you can avoid dealing with streams directly and achieve your result with:

List<String> lines = //...  

Path file = Paths.get("your path...");      
Files.write(file, lines, StandardCharsets.UTF_8,
    StandardOpenOption.APPEND, StandardOpenOption.CREATE);

You can pass multiple OptionOption values to the method. Here we pass CREATE and APPEND to tell NIO to create the file if it doesn't already exist and append to the file if it already exists.

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
  • I just read that the StandardOpenOption creates the file if it doesn't exist...This is exactly what I was looking for, thanks! – stepheaw Mar 05 '15 at 16:55
1

FileReader and FileWriter are old utility classes, needing a less verbose usage, but they use the default character encoding of the platform. That makes for non-portable data. Better is to use an additional InputStreamReader or OutputStreamWriter. They bridge from binary Streams to textual Reader/Writer by having a constructor with a specified encoding too.

For modern (shortened!) usage see Path, Paths and especially Files.

Path path = Paths.get("/etc/passwd");
try (BufferedReader in = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
    ...
} // Closes.
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
0

Since Java SE 7 there's the new NIO.2 File API. Especially the Files utility class can help you to create IO Streams.

I suggest to read the tutorial and come back if you have furhter questions.

Puce
  • 37,247
  • 13
  • 80
  • 152
-2

Java IO is fundamentally not changing:

  • BufferedWriter buffers the writing capabilities,
  • FileWriter allows you to write textual data to a file,
  • OutputStream allows you to write binary data.

You should use something like:

Writer writer = new BufferedWriter(new FileWriter(file, true)); // true to append data

Or use NIO.2.

Crazyjavahacking
  • 9,343
  • 2
  • 31
  • 40
  • 1
    There's the new NIO.2 File API. File is a legacy class and I would also consider FileWriter to be a legacy class (you would use one of the utility methods of Files). – Puce Mar 05 '15 at 16:52