Java java.io Package File Class

Java File class variables, constructors, methods, and examples for file and directory information

The File class can handle information about files and directories needed for input and output. It provides methods for obtaining information such as file and directory access permissions, creation time, last modification date, size, and path, and it also provides operation methods such as creating, deleting, and renaming files and directories.

File Class Variables

Variable Description
pathSeparator Path separator character (Windows: “;”, Linux and UNIX-like systems: “:”)
separator File name separator character (Windows: “", Linux and UNIX-like systems: “/”)

As mentioned earlier, Java is platform independent. Because Java can be compiled once and run regardless of OS, behavior sometimes needs to differ by OS. File paths and path separators differ by OS, so using these File class variables instead of directly typing strings helps implement programs without OS-specific errors.

File Constructors

Constructor Description
File(String pathname) Creates a file object for the specified pathname, including the file name.
File(String parent, String child) Creates an object for the child file under the parent directory path.
File(File parent, String child) Creates an object for the child file under the parent file object.
File(URI uri) Creates a file object for the uri path.

File Methods

File Query Methods

Method Description
File getAbsoluteFile() Returns the absolute path of the file.
String getAbsolutePath() Returns the absolute path of the file as a string.
File getCanonicalFile() Returns the canonical path of the file.
String getCanonicalPath() Returns the canonical path of the file as a string.
String getName() Returns the name of the file or folder.
String getParent() Returns the parent path name as a string.
File getParentFile() Returns the parent folder as a File.
String getPath() Returns the file path as a string.
long getTotalSpace() Returns the total capacity of the hard disk.
long getUsableSpace() Returns the usable capacity of the hard disk.
long getFreeSpace() Returns the remaining space on the hard disk.
int hashCode() Returns the hash code.
long lastModified() Returns the last modification date of the file at the path.
long length() Returns the length of the file at the path.
Path toPath() Returns it as a java.nio.file.Path object.
URI toURI() Returns the file path in URI form.
File[] listRoots() Returns root paths of hard disks.
String[] list() Returns files and folders at the path as a string array.
String[] list(FilenameFilter filter) Returns names of files and folders that satisfy filter as a string array.
File[] listFiles() Returns files and folders at the path as a File array.
File[] listFiles(FileFilter filter) Returns files and folders that satisfy filter as a File array.
File[] listFiles(FilenameFilter filter) Returns files and folders that satisfy filter as a File array.

File Operation Methods (Create, Modify, Delete)

Method Description
boolean createNewFile() Creates a new file if a file with the given name does not exist.
static File createTempFile(String prefix, String suffix) Creates a temporary file in the default temporary-file directory using prefix and suffix (.tmp if null).
static File createTempFile(String prefix, String suffix, File directory) Creates a temporary file in directory using the specified prefix and suffix (.tmp if null).
boolean delete() Deletes a file or directory. However, a directory cannot be deleted if it is not empty.
void deleteOnExit() Deletes the file when the Java virtual machine exits.
boolean mkdir() Creates a folder at the path. Returns true on success and false on failure.
boolean mkdirs() Creates a folder at the path, including nonexistent parent directories.
boolean renameTo(File dest) Changes the file to dest. This changes not only the name but also the path.

File Check Methods

Method Description
boolean exists() Returns whether the file exists.
boolean isAbsolute() Returns whether the path is an absolute path.
boolean isDirectory() Returns whether the path is a directory.
boolean isFile() Returns whether the path is a file.
boolean isHidden() Returns whether the path is a hidden file.

File Permission Methods

Method Description
boolean canExecute() Returns whether the file has execute permission.
boolean canRead() Returns whether the file has read permission.
boolean canWrite() Returns whether the file has write permission.
boolean setExecutable(boolean executable) Sets execute permission for the file owner.
boolean setExecutable(boolean executable, boolean ownerOnly) Sets execute permission for the owner or for everyone.
boolean setReadable(boolean readable) Sets read permission for the file owner.
boolean setReadable(boolean readable, boolean ownerOnly) Sets read permission for the owner or for everyone.
boolean setReadOnly() Changes the file to read-only.
boolean setWritable(boolean writable) Sets write permission for the file owner.
boolean setWritable(boolean writable boolean ownerOnly) Sets write permission for the owner or for everyone.

File Examples

Example 1
The following example displays information about a specific file.

package com.devkuma.tutorial.java.io;

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

public class FileClass {

    public static void main(String[] args) {

        // file.txt 객체 생성한다.
        File file = new File("file.txt");

        // 파일이 존재 여부를 체크한다.
        if (file.exists()) {

            try {
                // 파일 이름을 표시한다.
                System.out.println("getName: " + file.getName());
                // 파일 경로을 표시한다.
                System.out.println("getPath: " + file.getPath());
                // 파일 절대 경로 표시한다.
                System.out.println("getAbsolutePath : " + file.getAbsolutePath());
                // 파일 정규 경로 표시한다.
                System.out.println("getCanonicalPath : " + file.getCanonicalPath());
                // 상위 디렉터리를 표시한다.
                System.out.println("getParent : " + file.getParent());

                // 파일의 쓰기/읽기 권한 체크한다.
                if (file.canWrite())
                    System.out.println(file.getName() + " can write.");
                if (file.canRead())
                    System.out.println(file.getName() + " can read.");

                // 객체의 파일, 폴더 여부 체크한다.
                if (file.isFile()) {
                    System.out.println(file.getName() + " is file");
                }
                if (file.isDirectory()) {
                    System.out.println(file.getName() + " is directory.");
                }

                // 파일 내용 길이를 표시한다.
                System.out.println(file.getName() + " length=" + file.length());

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

        } else {
            System.out.println("not found file");
        }
    }
}

The execution result is as follows.

getName: file.txt
getPath: file.txt
getAbsolutePath : /Users/{user}/workspace/java-tutorial/file.txt
getCanonicalPath : /Users/{user}/workspace/java-tutorial/file.txt
getParent : null
file.txt can write.
file.txt can read.
file.txt is file
file.txt length=26

Example 2
The following example displays a list of files and directories in a specific directory.

package com.devkuma.tutorial.java.io;

import java.io.File;

public class FileClass2 {

    public static void main(String[] args) {

        // 프로젝트 현재 디렉터리를 객체로 생성한다.
        File file = new File(".");

        // 폴더의 파일/폴더 목록을 문자열 배열로 반환
        String[] files = file.list();

        // 출력
        for (String fileName : files) {
            System.out.println(fileName);
        }
    }
}

Execution result:

.classpath
.project
.settings
bin
file.txt
src

Example 3
The following example displays root paths and hard disk capacity on the screen.

package com.devkuma.tutorial.java.io;

import java.io.File;

public class FileClass3 {

    public static void main(String[] args) {

        // 하드디스크의 루트 경로(드라이브)들을 배열로 반환한다.
        File[] roots = File.listRoots();

        for (File root : roots) {

            // 루트 경로(드라이브)의 절대 경로
            String drive = root.getAbsolutePath();
            // 하드디스크 전체 용량
            long totalSpace = root.getTotalSpace();
            // 사용가능한 디스크 용량
            long usableSpace = root.getUsableSpace();
            // 여유 디스크 용량
            long freeSpace = root.getFreeSpace();
            // 사용한 디스크 용량
            long usedSpace = totalSpace - usableSpace;

            System.out.println("root : " + drive);
            System.out.println("Total Space : " + totalSpace);
            System.out.println("Usable Space : " + usableSpace);
            System.out.println("Free Space : " + freeSpace);
            System.out.println("Used Space : " + usedSpace);
        }
    }
}

Execution result:

root : /
Total Space : 598000009216
Usable Space : 100067610624
Free Space : 100329754624
Used Space : 497932398592