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.example.nio;

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     = 2012-11-28T00:08:55.290206Z
lastAccessTime   = 2012-11-28T00:08:55.290206Z
lastModifiedTime = 2012-11-28T00:08:55.291206Z
isDirectory      = false
isOther          = false
isRegularFile    = true
isSymbolicLink   = false
size             = 574

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 to content of a file. Let’s see the code below.

package org.kodejava.example.swing;

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

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

    private void initialize() {
        setSize(300, 300);
        setTitle("Populate JTextArea from File");
        setLayout(new BorderLayout());
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        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(
                    getClass().getResourceAsStream("/data.txt")),
                    null);
        } catch (IOException e) {
            e.printStackTrace();
        }

        getContentPane().add(scrollPane, BorderLayout.CENTER);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new PopulateTextAreaFromFile().setVisible(true);
            }
        });
    }
}

How do I read file using Scanner class?

Here is a compact way to read file line-by-line using the java.util.Scanner class.

package org.kodejava.example.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScannerReadFile {
    public static void main(String[] args) {
        // Create an instance of File for data.txt file.
        File file = new File("data.txt");
        try {
            // Create a new Scanner object which will read the data
            // from the file passed in. To check if there are more 
            // line to read from it we check by calling the 
            // scanner.hasNextLine() method. We then read line one 
            // by one till all line is read.
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

How do I create a directories recursively?

The code below use File.mkdirs() method to create a collection of directories recursively. It will create a directory with all its necessary parent directories.

package org.kodejava.example.util;

import java.io.File;

public class CreateDirs {
    public static void main(String[] args) {
        // Define a deep directory structures. Next we wanted to create all the
        // directories.
        String directories = "D:\a\b\c\d\e\f\g\h\i";
        File file = new File(directories);

        // The mkdirs will create folder including any necessary but non existence
        // parent directories. This method returns true if and only if the directory
        // was created along with all necessary parent directories.
        boolean result = file.mkdirs();
        System.out.println("Status = " + result);
    }
}

How can I change a file attribute to writable?

Prior to Java 1.6 the java.io.File class doesn’t include a method to change a read only file attribute and make it writable. To do this on the old days we have to utilize or called operating system specific command. But now in 1.6 a new method named setWritable() was introduced to do exactly what the method name says.

package org.kodejava.example.io;

import java.io.File;

public class WritableExample {
    public static void main(String[] args) throws Exception {
        File file = new File("Writable.txt");

        // Create a file only if it doesn't exist.
        file.createNewFile();

        // Set file attribute to read only so that it cannot be written
        file.setReadOnly();

        // We are using the canWrite() method to check whether we can
        // modified file content.
        if (file.canWrite()) {
            System.out.println("File is writable!");
        } else {
            System.out.println("File is in read only mode!");
        }

        // Now make our file writable
        file.setWritable(true);

        // re-check the read-write status of file 
        if (file.canWrite()) {
            System.out.println("File is writable!");
        } else {
            System.out.println("File is in read only mode!");
        }
    }
}

And here are the result of the code snippet above:

File is in read only mode!
File is writable!

How can I change a file attribute to read only?

This code demonstrate how we can modify file attribute to be read only. File class has a setReadOnly() method to make file read only and a canWrite() method to know whether it is writable or not.

package org.kodejava.example.io;

import java.io.File;

public class FileReadOnlyExample {
    public static void main(String[] args) throws Exception {
        File file = new File("ReadOnly.txt");

        // Create a file only if it doesn't exist.
        file.createNewFile();

        // Set file attribute to read only so that it cannot be written
        file.setReadOnly();

        // We are using the canWrite() method to check whether we can
        // modified file content.
        if (file.canWrite()) {
            System.out.println("File is writable!");
        } else {
            System.out.println("File is in read only mode!");
        }
    }
}

This code snippet print the following output:

File is in read only mode!

How do I determine if a pathname is a directory?

To determine if an abstract pathname is a directory we can use the File.isDirectory() method. Here is an example code.

package org.kodejava.example.io;

import java.io.File;

public class IsDirectoryExample {
    public static void main(String[] args) {
        // Creates a instance of File.
        File file = new File("/home/foo/bar");

        // Check if the abstract pathname is a directory by calling
        // isDirectory() method of the File class.
        if (file.isDirectory()) {
            System.out.println("This file is a directory.");
        } else {
            System.out.println("This is just an ordinary file.");
        }
    }
}

How do I rename a file or directory?

package org.kodejava.example.io;

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

public class FileRenameExample {
    public static void main(String[] args) throws IOException {
        // Creates a new file called OldHouses.csv
        File oldFile = new File("OldHouses.csv");
        oldFile.createNewFile();

        // Creates the target file.
        File newFile = new File("NewHouses.csv");

        // The renameTo() method renames file or directory to a
        // new name by passing the new destination file.
        oldFile.renameTo(newFile);
    }
}

How do I check if a file is hidden?

package org.kodejava.example.io;

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

public class FileHiddenExample {
    public static void main(String[] args) throws IOException {
        File file = new File("Hidden.txt");
        file.createNewFile();

        // We are using the isHidden() method to check whether a file
        // is hidden.
        if (file.isHidden()) {
            System.out.println("File is hidden!");
        } else {
            System.out.println("File is not hidden!");
        }
    }
}

If you want to set the file attribute to hidden in Windows operating system you can see it in the following example: How do I set the value of file attributes?

How do I get the content of a directory?

In this example you’ll see how to read the list of files inside a directory. To get this functionality we can use the File.listFiles() method. This method return an array of File object which can be either an instance of file or directory.

package org.kodejava.example.io;

import java.io.File;
import java.io.FilenameFilter;

public class DirectoryContentExample {
    public static void main(String[] args) {
        File gamesDir = new File("D:/Games");

        // Get a list of file under the specified directory
        // above and return it as an abstract file object.
        File[] files = gamesDir.listFiles();

        // Iterates the content of gamesDir directory, print it
        // and check it whether it was a directory or a file.
        for (File file : files) {
            System.out.println(file + " is a "
                    + (file.isDirectory() ? "directory" : "file"));
        }

        // Here we also get the list of file in the directory but
        // return it just as an array of String.
        String[] strings = gamesDir.list();
        for (String file : strings) {
            System.out.println("File = " + file);
        }

        // Now we want to list the file in the directory but
        // we just want a file with a .doc extension. To do
        // this we first create a FilenameFilter which will
        // be given to the listFiles() method to filter the
        // listing process. The rule of filtering is
        // implemented in the accept() method of the
        // FilenameFilter interface.
        FilenameFilter filter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.endsWith(".doc");
            }
        };

        // Give me just a .doc files in your directory.
        File[] docs = gamesDir.listFiles(filter);
        for (File doc : docs) {
            System.out.println("Doc file = " + doc);
        }
    }
}

Here is the result of the program:

The File[] array returned:

D:\Games\AOE\ is a directory
D:\Games\Championship Manager 2007 is a directory
D:\Games\GameHouse is a directory
D:\Games\Sierra is a directory
D:\Games\testing.doc is a file
D:\Games\TTD is a directory

The String[] array returned:

File = AOE
File = Championship Manager 2007
File = GameHouse
File = Sierra
File = testing.doc
File = TTD

The File[] array using FilenameFilter result:

Doc file = D:\Games\testing.doc