Java FileWriter
Java FileWriter
is a class that writes characters to a file in the file system. It is a subclass of the OutputStreamWriter
class, which is a bridge between byte streams and character streams.
Here's an example of how to use FileWriter
to write to a file:
try (FileWriter writer = new FileWriter("example.txt")) { writer.write("Hello, world!"); } catch (IOException e) { e.printStackTrace(); }
In this example, we create a new FileWriter
object and pass the name of the file we want to write to ("example.txt") as a parameter. We then call the write()
method to write the string "Hello, world!" to the file. Note that we use a try-with-resources statement to automatically close the FileWriter
when we're done with it, and we catch any IOException
that might occur during the write operation.
By default, the FileWriter
class overwrites the contents of the file if it already exists. If you want to append to the end of the file instead, you can use the FileWriter(String fileName, boolean append)
constructor and pass true
as the second parameter:
try (FileWriter writer = new FileWriter("example.txt", true)) { writer.write("This text will be appended to the end of the file."); } catch (IOException e) { e.printStackTrace(); }
This example will append the string "This text will be appended to the end of the file." to the end of the "example.txt" file, rather than overwriting its contents.