In the below examples, we are going to create text file (sample.txt) with below content.

Hello, it's a great day today!
using java.nio.Files public void writeToFileUsingFiles(String text, String fullyQualifiedPath) throws IOException { Files.writeString(Path.of(fullyQualifiedPath), text); }

You can also pass file OpenOption arguments to method, for example if you want to append the text to an existing file, then you can use as shown in below example, default behaviour is that it overrides the content.

Third parameter to method takes an optional array of . For the full list of File OpenOptions, read through this Java - File Open Options

public void writeToFileUsingFiles(String text, String fullyQualifiedPath) throws IOException { Files.writeString(Path.of(fullyQualifiedPath), text, StandardOpenOption.APPEND); }
using java.io.FileWriter public void writeToFileUsingFileWriter(String text, String fullyQualifiedPath) throws IOException { try (FileWriter fileWriter = new FileWriter(fullyQualifiedPath)) { fileWriter.write(text); } }

In the above code, FileWriter.write(String) method writes input String into the file.

Default behaviour of above code is it always overrides the content. If you want to append text to the file instead, you can enable append=true at FileWriter level by using constructor as shown below. Below is the example code to append text.

public void appendToFileUsingFileWriter(String text, String fullyQualifiedPath) throws IOException { try (FileWriter fileWriter = new FileWriter(fullyQualifiedPath, true)) { fileWriter.write(text); } }
using java.io.BufferedWriter
To obtain BufferedWriter instance, we could also use .
public void writeToFileUsingBufferedWriter(String text, String fullyQualifiedPath) throws IOException { try(BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fullyQualifiedPath))) { bufferedWriter.write(text); } }

Above examples source code can be found at GitHub link for Java code and JUnit tests can be found at GitHub link for Unit tests code