Writing a File

JavaJavaBeginner
Practice Now

Introduction

In this lab, we will learn how to write data to a file using Java programming language. Writing data to a file can be very useful when you need to store data generated by your program for future use.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/FileandIOManagementGroup(["`File and I/O Management`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/generics("`Generics`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/packages_api("`Packages / API`") java/FileandIOManagementGroup -.-> java/nio("`NIO`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/SystemandDataProcessingGroup -.-> java/string_methods("`String Methods`") subgraph Lab Skills java/scope -.-> lab-117457{{"`Writing a File`"}} java/generics -.-> lab-117457{{"`Writing a File`"}} java/classes_objects -.-> lab-117457{{"`Writing a File`"}} java/class_methods -.-> lab-117457{{"`Writing a File`"}} java/modifiers -.-> lab-117457{{"`Writing a File`"}} java/oop -.-> lab-117457{{"`Writing a File`"}} java/packages_api -.-> lab-117457{{"`Writing a File`"}} java/nio -.-> lab-117457{{"`Writing a File`"}} java/identifier -.-> lab-117457{{"`Writing a File`"}} java/arrays -.-> lab-117457{{"`Writing a File`"}} java/data_types -.-> lab-117457{{"`Writing a File`"}} java/operators -.-> lab-117457{{"`Writing a File`"}} java/strings -.-> lab-117457{{"`Writing a File`"}} java/variables -.-> lab-117457{{"`Writing a File`"}} java/string_methods -.-> lab-117457{{"`Writing a File`"}} end

Open/Create a file

The first step is to open or create a file that we want to write the data to. We will create a new file called output.txt in the ~/project directory.

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

public class Main {
    public static void main(String[] args) {
        Path path = Paths.get("~/project/output.txt");
    }
}

Write a string to a file

Now that we have our file open, we can write a string to it. This is done using the Files.write() method.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.charset.StandardCharsets;

public class Main {
    public static void main(String[] args) throws IOException {
        Path path = Paths.get("~/project/output.txt");
        String content = "This is some text that we want to write to the file";

        Files.write(path, content.getBytes());
    }
}

Here, we are writing a string to the file by converting it to bytes and passing it to the Files.write() method. Note that we need to use getBytes() method to convert the string to bytes.

To run the above code in your terminal, first, you need to navigate to your project directory in the terminal. Then, execute the following command:

javac Main.java && java Main

Write a List of string to a file

We can also write a list of strings to the file using Files.write() method, as follows:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) throws IOException {
        Path path = Paths.get("~/project/output.txt");
        List<String> lines = Arrays.asList("This is line 1", "This is line 2", "This is line 3");

        Files.write(path, lines, StandardCharsets.UTF_8);
    }
}

Here, we are writing a list of strings to the file. Note that we are using an overloaded version of the Files.write() method that takes a list of strings as a parameter.

To execute the above code for writing list of strings to the file, first, you need to navigate to your project directory in the terminal. Then, execute the following command:

javac Main.java && java Main

Append to a file

If you want to write data to a file without overwriting existing data in the file, you can use the StandardOpenOption.APPEND option when opening the file. This will append any new data to the end of the file.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.nio.file.StandardOpenOption;

public class Main {
    public static void main(String[] args) throws IOException {
        Path path = Paths.get("~/project/output.txt");
        List<String> lines = Arrays.asList("This is line 4", "This is line 5", "This is line 6");

        Files.write(path, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
    }
}

Here, we have added an option StandardOpenOption.APPEND to the Files.write() method, which tells Java to append new data to the end of the file, rather than overwriting any existing data.

To execute the append operation, first, you need to navigate to your project directory in the terminal. Then, execute the following command:

javac Main.java && java Main

Close the file

Finally, we need to close the file using the Files.close() method. This will ensure that any buffered data is written to the file before it is closed.

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.nio.file.StandardOpenOption;

public class Main {
    public static void main(String[] args) throws IOException {
        Path path = Paths.get("~/project/output.txt");
        String content = "This is some text that we want to write to the file";

        Files.write(path, content.getBytes());
        Files.write(path, System.lineSeparator().getBytes(), StandardOpenOption.APPEND);
        Files.write(path, "This is a new line".getBytes(), StandardOpenOption.APPEND);

        Files.close();
    }
}

Summary

In this lab, we have learned how to write data to a file using Java's Files class. We have seen how to write a string to a file, write a list of strings to a file, append to a file, and close a file. We hope now you can write a file easily with the help of Java's Files class.

Other Java Tutorials you may like