How do I write a text file in JDK 7?

In JDK 7 we can write all lines from a List of String into a file using the Files.write() method. We need to provide the Path of the file we want to write to, the List of strings and the charsets. Each line is a char sequence and is written to the file in sequence with each line terminated by the platform’s line separator.

Let’s see the code snippet below:

package org.kodejava.io;

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

public class WriteTextFile {
    public static void main(String[] args) {
        Path file = Paths.get("D:/resources/data.txt");

        List<String> lines = new ArrayList<>();
        lines.add("Lorem Ipsum is simply dummy text of the printing ");
        lines.add("and typesetting industry. Lorem Ipsum has been the ");
        lines.add("industry's standard dummy text ever since the 1500s, ");
        lines.add("when an unknown printer took a galley of type and ");
        lines.add("scrambled it to make a type specimen book.");

        try {
            // Write lines of text to a file.
            Files.write(file, lines, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

This code snippet will create a file called data.txt under the resources folder. Please make sure that this folder is existed before you tried to run the code.

How do I get file basic attributes?

This example you’ll learn how to get file’s basic attributes. Basic file attributes are attributes that are common to many file systems and consist of mandatory and optional file attributes as defined by the BasicFileAttributes interface.

The file’s basic attributes include file’s date time information such as the creation time, last access time, last modified time. You can also check whether the file is a directory, a regular file, a symbolic link or something else. You can also get the size of the file.

Let’s see the code snippet below:

package org.kodejava.io;

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

public class FileAttributesDemo {
    public static void main(String[] args) throws Exception {
        String path = "D:/resources/data.txt";

        Path file = Paths.get(path);
        BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);
        System.out.println("creationTime     = " + attr.creationTime());
        System.out.println("lastAccessTime   = " + attr.lastAccessTime());
        System.out.println("lastModifiedTime = " + attr.lastModifiedTime());

        System.out.println("isDirectory      = " + attr.isDirectory());
        System.out.println("isOther          = " + attr.isOther());
        System.out.println("isRegularFile    = " + attr.isRegularFile());
        System.out.println("isSymbolicLink   = " + attr.isSymbolicLink());
        System.out.println("size             = " + attr.size());
    }
}

The output of the code snippet:

creationTime     = 2021-05-05T17:09:09.0628061Z
lastAccessTime   = 2021-05-05T17:09:09.0628061Z
lastModifiedTime = 2021-11-04T00:11:43.279Z
isDirectory      = false
isOther          = false
isRegularFile    = true
isSymbolicLink   = false
size             = 0

How do I set file last modified time?

In the following code snippet you will learn how to update file’s last modified date/time. To update the last modified date/time you can use the java.nio.file.Files.setLastModifiedTime() method. This method takes two arguments. The first arguments is a Path object that represent a file, and the second arguments is the modified date in a FileTime object.

Let’s try the code snippet below.

package org.kodejava.io;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;

public class SettingFileTimeStamps {
    public static void main(String[] args) throws Exception {
        String path = "D:/resources/data.txt";
        Path file = Paths.get(path);

        BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);
        System.out.println("lastModifiedTime() = " + attr.lastModifiedTime());

        // Update the last modified time of the file.
        long currentTimeMillis = System.currentTimeMillis();
        FileTime fileTime = FileTime.fromMillis(currentTimeMillis);
        Files.setLastModifiedTime(file, fileTime);

        attr = Files.readAttributes(file, BasicFileAttributes.class);
        System.out.println("lastModifiedTime() = " + attr.lastModifiedTime());
    }
}

The output of the code snippet:

lastModifiedTime() = 2021-05-05T17:09:09.0628061Z
lastModifiedTime() = 2021-11-04T00:11:43.279Z

How do I read file using FileInputStream?

The following example use the java.io.FileInputStream class to read contents of a text file. We’ll read a file located in the temporary directory defined by operating system. This temporary directory can be accessed using the java.io.tmpdir system property.

package org.kodejava.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStreamDemo {
    public static void main(String[] args) {
        // Get the temporary directory. We'll read the data.txt file
        // from this directory.
        String tempDir = System.getProperty("java.io.tmpdir");
        File file = new File(tempDir + "/data.txt");

        StringBuilder builder = new StringBuilder();
        FileInputStream fis = null;
        try {
            // Create a FileInputStream to read the file.
            fis = new FileInputStream(file);

            int data;
            // Read the entire file data. When -1 is returned it
            // means no more content to read.
            while ((data = fis.read()) != -1) {
                builder.append((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        // Print the content of the file
        System.out.println("File Contents = " + builder);
    }
}

The content read from the input stream will be appended into a StringBuilder object. At the end of the snippet the content of the will be converted into string using the toString() method.

Here are the content of our data.txt file.

File Contents = Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

How do I read all lines from a file?

The java.nio.file.Files.readAllLines() method read all lines from a file. This method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown. Bytes from the file are decoded into characters using the specified charset.

Note that this method is intended for simple cases where it is convenient to read all lines in a single operation. It is not intended for reading in large files. This method is available since Java 7.

package org.kodejava.io;

import java.net.URI;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;

public class ReadFileAsListDemo {
    public static void main(String[] args) {
        ReadFileAsListDemo demo = new ReadFileAsListDemo();
        demo.readFileAsList();
    }

    private void readFileAsList() {
        String fileName = "/data.txt";

        try {
            URI uri = Objects.requireNonNull(this.getClass().getResource(fileName)).toURI();
            List<String> lines = Files.readAllLines(Paths.get(uri),
                    Charset.defaultCharset());

            for (String line : lines) {
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}