Java - How to write Text(String) to a file

In Java, you can write text to a file using the following classes.

  • BufferedWriter
  • PrintWriter
  • FileOutputStream
  • Files

Let`s see with an example.

Write a file using BufferedWriter

The following is an example of writing text to the text.txt file using BufferedWriter.

File file = new File("/home/js/test/text.txt");
String str = "Hello world!";

try {
    BufferedWriter writer = new BufferedWriter(new FileWriter(file));
    writer.write(str);
    writer.close();
} catch (IOException e) {
    e.printStackTrace();
}

If the file doesn`t exist, it creates a file, enters text and saves it.

Importantly, if you use a BufferedWriter, you must close the FileDescriptor by calling close() at the end.

If we use Try-with-resources like the code below, we dont need to call it because try calls close()` at the end.

File file = new File("/home/js/test/text.txt");
String str = "Hello world!";

try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
    writer.write(str);
} catch (IOException e) {
    e.printStackTrace();
}

You can use append() instead of append() to enter text multiple times.

File file = new File("/home/js/test/text.txt");

try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
    writer.append("Hello~\n");
    writer.append("World!");
} catch (IOException e) {
    e.printStackTrace();
}

Write a file using PrintWriter

The following is an example of writing text to a file with PrintWriter.

File file = new File("/home/js/test/text.txt");
try {
    FileWriter fileWriter = new FileWriter(file);
    PrintWriter printWriter = new PrintWriter(fileWriter);
    printWriter.print("Hello~\n");
    printWriter.print("World!");
    printWriter.close();
} catch (IOException e) {
    e.printStackTrace();
}

You can input multiple texts with print(). You must also call close() at the end of this.

If we implement it using Try-with-resources like this, we dont have to call close()`.

File file = new File("/home/js/test/text.txt");
try (FileWriter fileWriter = new FileWriter(file)) {
    PrintWriter printWriter = new PrintWriter(fileWriter);
    printWriter.print("Hello~\n");
    printWriter.print("World!");
} catch (IOException e) {
    e.printStackTrace();
}

Write a file using FileOutputStream

The following is an example of writing text to a file using FileOutputStream. You need to convert String to byte and write to Stream.

File file = new File("/home/js/test/text.txt");
String str = "Hello World";
byte[] bytes = str.getBytes();
try {
    FileOutputStream outputStream = new FileOutputStream(file);
    outputStream.write(bytes);
    outputStream.close();
} catch (IOException e) {
    e.printStackTrace();
}

You can also implement it using Try-with-resources like this:

File file = new File("/home/js/test/text.txt");
String str = "Hello World";
byte[] bytes = str.getBytes();
try (FileOutputStream outputStream = new FileOutputStream(file)) {
    outputStream.write(bytes);
} catch (IOException e) {
    e.printStackTrace();
}

Write a file using Files

The following code is an example of writing a string to a file using Files.

String str = "Hello";
byte[] bytes = str.getBytes();
Path path = Paths.get("/home/js/test/text.txt");
try {
    Files.write(path, bytes);
} catch (IOException e) {
    e.printStackTrace();
}

Convert String to byte and pass it as an argument to write().

Inside Files.write() write string to file as OutputStream. It also calls close() so we dont have to call close()`.

For reference, the code below is the actual implementation code of Java Files.write().

public static Path write(Path path, byte[] bytes, OpenOption... options)
    throws IOException
{
    // ensure bytes is not null before opening file
    Objects.requireNonNull(bytes);

    try (OutputStream out = Files.newOutputStream(path, options)) {
        int len = bytes.length;
        int rem = len;
        while (rem > 0) {
            int n = Math.min(rem, BUFFER_SIZE);
            out.write(bytes, (len-rem), n);
            rem -= n;
        }
    }
    return path;
}

Reference

codechachaCopyright ©2019 codechacha