0

I am new to java programming and looking for options to write and append file content with java.

Similar options for below C# options.

File.WriteAllText(string path, string contents, Encoding encoding);
File.AppendAllText(string path, string contents, Encoding encoding);

I though to use BufferedWriter, it have option to pass true/false for FileWriter(String path, boolean append) but i don't have option to provide Encoding.

try (FileWriter fw = new FileWriter(path, false);
    BufferedWriter bw = new BufferedWriter(fw)) {
    bw.write("appending text into file");
}

If I initialize BufferedWriter with Files.newBufferedWriter, I can provide StandardCharsets, but it don't have option to append in case of existing file.

try (BufferedWriter bw = Files.newBufferedWriter(Paths.get(path), StandardCharsets.UTF_8)) {
    bw.write("test");
    bw.append("append test");
}

Is it possible to define both option together (Append options and StandardCharsets)?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Krupa
  • 457
  • 3
  • 14

2 Answers2

1

Yes. if you look into the Files class implementation, there is a method as follows:

public static BufferedWriter newBufferedWriter(Path path, Charset cs, OpenOption... options)

so you can call a method like

BufferedWriter bw = Files.newBufferedWriter(Paths.get(path), StandardCharsets.UTF_8, 
                    StandardOpenOption.CREATE, StandardOpenOption.APPEND)

If you use a IDE like Intellij, it would suggest what public methods you are allowed to call.

夢のの夢
  • 5,054
  • 7
  • 33
  • 63
0

You can give a try to java.nio in order to append content to an existing file (if you are using Java 7 or above), maybe you can do something like this:

List<String> newContent = getNewContent(...); // Here you get the lines you want to add
Files.write(myFile, newContent, UTF_8, APPEND, CREATE);

The imports will need to be done by:

java.nio.charset.StandardCharsets.UTF_8, java.nio.file.StandardOpenOption.APPEND, java.nio.file.StandardOpenOption.CREATE

Or you can try using Guava:

File myFile = new File("/Users/home/dev/log.txt");
String newContent = "This is new content";
Files.append(newContent, myFile, Charsets.UTF_8);
Marcelo Tataje
  • 3,849
  • 1
  • 26
  • 51