Java FileWriterWithEncoding-class And Method Code Example

Here is an example of using the FileWriterWithEncoding class from the Apache Commons IO library in Java to write text to a file with a specific encoding:


public class FileWriterWithEncodingExample {
    public static void main(String[] args) {
        // specify the file to write to
        File file = new File("/path/to/file.txt");
        // specify the encoding
        String encoding = "UTF-8";
        try (FileWriterWithEncoding writer = new FileWriterWithEncoding(file, encoding)) {
            // write text to the file
            writer.write("This is some text to be written to the file with UTF-8 encoding.");
        } catch (IOException e) {

In this example, a FileWriterWithEncoding object is created by passing the file to write to and the encoding as arguments, in this case, "UTF-8". The FileWriterWithEncoding class extends the FileWriter class, but it allows you to specify the encoding when creating the object.

The write() method is used to write text to the file.

The FileWriterWithEncoding class provides a way to write text to a file using a specific encoding, this is useful when working with text files that contain characters that are not part of the default encoding of the system. By explicitly specifying the encoding, you can ensure that the text is written to the file correctly and can be read correctly on any system that supports that encoding.