Java IO - Write to file

October 21, 2019 No comments Java IO File write

1. Introduction

In this article, we will explore different ways to write the content to a file in Java. There are several different methods you can use to do it. We will give some advice about which method is the best for writing different data types. It can be helpful for you to choose the best method that will suit your needs.

2. Write with BufferedWriter

BufferedWriter is used to write the string content into a file in Java. This writer was specially designed to write text to a character-output stream. It supports buffering characters to improve writing efficiency.

package com.frontbackend.java.io.write;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class WriteToFileUsingBufferedWriter {

    public static void main(String[] args) {

        try (BufferedWriter writer = new BufferedWriter(new FileWriter("/tmp/test1.txt"))) {
            writer.write("FrontBackend.com");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. Write with FileOutputStream

FileOutputStream was designed to write binary data into a file. In the following example, we get bytes from a simple String and writes them to file using FileOutputStream for the sake of simplicity.

package com.frontbackend.java.io.write;

import java.io.FileOutputStream;
import java.io.IOException;

public class WriteToFileUsingFileOutputStream {

    public static void main(String[] args)  {
        final String content = "FrontBackend.com";

        try (FileOutputStream outputStream = new FileOutputStream("/tmp/test2.txt")) {
            byte[] strToBytes = content.getBytes();
            outputStream.write(strToBytes);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

4. Write with PrintWriter

PrintWriter writes formatted representations of objects to a text-output stream. This writer proivdes all methods available in PrintStream, so you can print to a file all kind of Java objects and primitive types.

package com.frontbackend.java.io.write;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class WriteToFileUsingPrintWriter {

    public static void main(String[] args) throws IOException {
        final String content = "FrontBackend.com";

        FileWriter fileWriter = new FileWriter("/tmp/test4.txt");
        PrintWriter printWriter = new PrintWriter(fileWriter);
        printWriter.print(content);
        printWriter.printf("This %s blog is awesome", "frontbackend.com");
        printWriter.close();
    }
}

5. Write with FileWriter

FileWriter is meant for writing streams of characters into a file. In the following example we write simple String FrontBackend.com to a file located in /tmp/test3.txt.

package com.frontbackend.java.io.write;

import java.io.FileWriter;
import java.io.IOException;

public class WriteToFileUsingFileWriter {

    public static void main(String[] args) {
        final String content = "FrontBackend.com";

        try (FileWriter fileWriter = new FileWriter("/tmp/test3.txt")) {
            fileWriter.write(content);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

6. Write with DataOutputStream

DataOutputStream can be used to write bytes, primitive types, characters and Strings into a file. It has implemented writeUTF method that writes a string to the underlying output stream using modified UTF-8 encoding.

package com.frontbackend.java.io.write;

import java.io.*;

public class WriteToFileUsingDataOutputStream {

    public static void main(String[] args) throws IOException {
        final String content = "FrontBackend.com";

        FileOutputStream outputStream = new FileOutputStream("/tmp/test4.txml");
        DataOutputStream dataOutStream = new DataOutputStream(new BufferedOutputStream(outputStream));
        dataOutStream.writeUTF(content);

        dataOutStream.close();
    }
}

7. Write with FileChannel

FileChannel is a universal object used for reading, writing, mapping, locking and manipulating a file. File channels are safe for use by multiple concurrent threads.

package com.frontbackend.java.io.write;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class WriteToFileUsingFileChannel {

    public static void main(String [] args) throws IOException {
        String content = "FrontBackend.com";

        RandomAccessFile stream = new RandomAccessFile("/tmp/text5.txt", "rw");
        FileChannel channel = stream.getChannel();
        byte[] strBytes = content.getBytes();
        ByteBuffer buffer = ByteBuffer.allocate(strBytes.length);
        buffer.put(strBytes);
        buffer.flip();
        channel.write(buffer);
        stream.close();
        channel.close();
    }
}

8. Write with Files

JDK 7 introduce Files utility class. This class comes with static methods that operate on files, directories, or other types of files. Using Files object you can write a string to a file in a single line of code.

package com.frontbackend.java.io.write;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class WriteToFileUsingFileChannel {

    public static void main(String[] args) throws IOException {
        Path path = Paths.get("/temp/test6.txt");
        Files.write(path, "FrontBackend.com".getBytes());
    }
}

9. Conclusion

This article lists several methods used to write content into a file in Java. Different Java writers are meant for different data types. For printing formatted text into a file use PrintWriter class, FileChannel is great for large files, FileOutputStream can write any binary data and DataOutputStream can write also primitive data types like int, long or double.

{{ message }}

{{ 'Comments are closed.' | trans }}