How do I created tab delimited data file in Java?

The following code snippet show you how to create a tab delimited data file in Java. The tab character is represented using the \t sequence of characters, a backslash (\) character followed by the t letter. In the code below we start by defining some data that we are going to write to the file.

We create a PrintWriter object, passes a BufferedWritter created using the Files.newBufferedWriter() method. The countries.dat is the file name where the data will be written. Because we are using the try-with-resources the PrintWriter and the related object will be closed automatically when the file operation finishes.

package org.kodejava.io;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class TabDelimitedDataFile {
    public static void main(String[] args) throws IOException {
        List<String[]> data = new ArrayList<>();
        data.add(new String[]{"Afghanistan", "AF", "AFG", "004", "Asia"});
        data.add(new String[]{"Åland Islands", "AX", "ALA", "248", "Europe"});
        data.add(new String[]{"Albania", "AL", "ALB", "008", "Europe"});
        data.add(new String[]{"Algeria", "DZ", "DZA", "012", "Africa"});
        data.add(new String[]{"American Samoa", "AS", "ASM", "016", "Polynesia"});
        data.add(new String[]{"Andorra", "AD", "AND", "020", "South Europe"});
        data.add(new String[]{"Angola", "AO", "AGO", "024", "Africa"});
        data.add(new String[]{"Anguilla", "AI", "AIA", "660", "Americas"});
        data.add(new String[]{"Antarctica", "AQ", "ATA", "010", ""});
        data.add(new String[]{"Argentina", "AR", "ARG", "032", "Americas"});

        try (PrintWriter writer = new PrintWriter(
                Files.newBufferedWriter(Paths.get("countries.dat")))) {
            for (String[] row : data) {
                writer.printf("%1$20s\t%2$3s\t\t%3$3s\t\t%4$3s\t\t%5$s",
                        row[0], row[1], row[2], row[3], row[4]);
                writer.println();
            }
        }
    }
}

The output of the code snippet above are:

         Afghanistan     AF     AFG     004     Asia
       Åland Islands     AX     ALA     248     Europe
             Albania     AL     ALB     008     Europe
             Algeria     DZ     DZA     012     Africa
      American Samoa     AS     ASM     016     Polynesia
             Andorra     AD     AND     020     South Europe
              Angola     AO     AGO     024     Africa
            Anguilla     AI     AIA     660     Americas
          Antarctica     AQ     ATA     010     
           Argentina     AR     ARG     032     Americas

How to read text file contents line by line?

In the following code example you will learn how to read file contents line by line using the Apache Commons FileUtils.lineIterator() method. Reading file contents one line at a time, do some processing, and release it from memory immediately will lower the memory consumption used by your program.

The snippet below give you the basic usage of the FileUtils.lineIterator() method. You pass the file to read and the encoding to use. An Iterator of the lines in the file will be returned. Use the hasNext() method to see if there are lines to read from the iterator. The nextLine() method will give you the next line from the file.

When we finished with the iterator we need to close it using the LineIterator.close() or LineIterator.closeQuietly() method.

package org.kodejava.commons.io;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;

import java.io.File;
import java.net.URL;
import java.util.Objects;

public class ReadFileLineByLine {
    public static void main(String[] args) throws Exception {
        // Load file from resource directory.
        ClassLoader classLoader = ReadFileLineByLine.class.getClassLoader();
        URL url = Objects.requireNonNull(classLoader.getResource("data.txt"),
                "Resource could not be found.");

        File file = new File(url.getFile());
        try (LineIterator iterator = FileUtils.lineIterator(file, "UTF-8")) {
            while (iterator.hasNext()) {
                String line = iterator.nextLine();
                System.out.println("line = " + line);
            }
        }
    }
}

In the example above we load the file from a resource directory. That’s why we use the ClassLoader.getResource() method. If you want to load a file from an absolute path you can simply create a File object and pass the absolute path to the file.

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>

Maven Central

How do I copy a file in JDK 7?

In this example you’ll see how to copy a file using the new API provided in the JDK 7. The first step is to define the source and the target of the file to be copied. For this we can use the Path class. To create an instance of Path we use the Paths.get() method by passing the path information as the arguments.

Next we can configure the file copy operation option. For this we can define it as an array of CopyOtion. We can use copy option such as StandardCopyOption.REPLACE_EXISTING and StandardCopyOption.COPY_ATTRIBUTES.

Finally, to copy the file we use the Files.copy() method. We give three arguments to this method, they are the source file, the target file and the copy options information.

Let’s see the code snippet below:

package org.kodejava.io;

import java.io.IOException;
import java.nio.file.*;

public class NioFileCopyDemo {
    public static void main(String[] args) {
        // Define the source and target of the file to be copied.
        Path source = Paths.get("D:/resources/data.txt");
        Path target = Paths.get("D:/resources/data.bak");

        // Define the options used in the file copy process.
        CopyOption[] options = new CopyOption[]{
                StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.COPY_ATTRIBUTES
        };

        try {
            // Copy file from source to target using the defined 
            // configuration.
            Files.copy(source, target, options);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How do I set the value of file attributes?

This code snippet show you an example on how to set the value of file attributes. Here we will set the DosFileAttributes. To set the value of file attributes we use the Files.setAttributes() method. To set DosFileAttributes we can use the following attributes: "dos:archive", "dos:hidden", "dos:readonly" and "dos:system".

For details 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.DosFileAttributes;

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

        // Get current Dos file attributes and print it.
        DosFileAttributes attr = Files.readAttributes(file, DosFileAttributes.class);
        printAttributes(attr);

        // Set a new file attributes.
        Files.setAttribute(file, "dos:archive", false);
        Files.setAttribute(file, "dos:hidden", false);
        Files.setAttribute(file, "dos:readonly", false);
        Files.setAttribute(file, "dos:system", false);

        // Read the newly set file attributes and print it.
        attr = Files.readAttributes(file, DosFileAttributes.class);
        printAttributes(attr);
    }

    /**
     * Print the DosFileAttributes information.
     *
     * @param attr DosFileAttributes.
     */
    private static void printAttributes(DosFileAttributes attr) {
        System.out.println("isArchive()  = " + attr.isArchive());
        System.out.println("isHidden()   = " + attr.isHidden());
        System.out.println("isReadOnly() = " + attr.isReadOnly());
        System.out.println("isSystem()   = " + attr.isSystem());
        System.out.println("----------------------------------------");
    }
}

The output of the code snippet:

isArchive()  = true
isHidden()   = true
isReadOnly() = true
isSystem()   = true
----------------------------------------
isArchive()  = false
isHidden()   = false
isReadOnly() = false
isSystem()   = false
----------------------------------------

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 text file into JTextArea?

Using the read(Reader in, Object desc) method inherited from the JTextComponent allow us to populate a JTextArea with text content from a file. This example will show you how to do it.

In this example we use an InputStreamReader to read a file from our application resource. You could use other Reader implementation such as the FileReader to read the content of a file. Let’s see the code below.

package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Objects;

public class PopulateTextAreaFromFile extends JPanel {
    public PopulateTextAreaFromFile() {
        initialize();
    }

    public static void showFrame() {
        JPanel panel = new PopulateTextAreaFromFile();
        panel.setOpaque(true);

        JFrame frame = new JFrame("Populate JTextArea from File");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(PopulateTextAreaFromFile::showFrame);
    }

    private void initialize() {
        JTextArea textArea = new JTextArea();
        JScrollPane scrollPane = new JScrollPane(textArea);
        try {
            // Read some text from the resource file to display in
            // the JTextArea.
            textArea.read(new InputStreamReader(Objects.requireNonNull(
                    getClass().getResourceAsStream("/data.txt"))), null);
        } catch (IOException e) {
            e.printStackTrace();
        }

        this.setPreferredSize(new Dimension(500, 200));
        this.setLayout(new BorderLayout());
        this.add(scrollPane, BorderLayout.CENTER);
    }
}

The output of the code snippet above is:

Read Text File into JTextArea

How do I get the extension of a file?

Below is an example that can be used to get the extension of a file. The code below assume that the extension is the last part of the file name after the last dot symbol. For instance if you have a file named data.txt the extension will be txt, but if you have a file named data.tar.gz the extension will be gz.

package org.kodejava.io;

import java.io.File;

public class FileExtension {
    private static final String EXT_SEPARATOR = ".";

    public static void main(String[] args) {
        File file = new File("data.txt");
        String ext = FileExtension.getFileExtension(file);
        System.out.println("Ext = " + ext);

        file = new File("F:/Temp/Data/data.tar.gz");
        ext = FileExtension.getFileExtension(file);
        System.out.println("Ext = " + ext);

        file = new File("F:/Temp/Data/HelloWorld.java");
        ext = FileExtension.getFileExtension(file);
        System.out.println("Ext = " + ext);
    }

    /**
     * Get the extension of the specified file.
     *
     * @param file a file.
     * @return the extension of the file.
     */
    private static String getFileExtension(File file) {
        if (file == null) {
            return null;
        }

        String name = file.getName();
        int extIndex = name.lastIndexOf(FileExtension.EXT_SEPARATOR);

        if (extIndex == -1) {
            return "";
        } else {
            return name.substring(extIndex + 1);
        }
    }
}

How do I print a file using the default registered application?

The example code below shows you how to print a file using the default registered application’s print command for the corresponding file type. As an example, on Windows notepad.exe is the default application for printing a .txt file.

To print a file using the default registered application we call the java.awt.Desktop.print(File) method. The print() method takes a parameter of File, which is the reference to a file to be printed. The code snippet below, when run on Windows, will open notepad.exe and print the data.txt file.

package org.kodejava.awt;

import java.awt.*;
import java.io.File;
import java.io.IOException;

public class RunningDefaultAppPrint {
    public static void main(String[] args) {
        File file = new File("data.txt");
        try {
            Desktop desktop = Desktop.getDesktop();

            // Prints a file with the native desktop printing facility, 
            // using the associated application's print command.
            desktop.print(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}