Files

The File class is an abstract representation of file and directory pathnames.

User interfaces and operating systems use system-dependent pathname strings to name files and directories. The conversion of a pathname string to or from an abstract pathname is inherently system-dependent.

The definition of absolute pathname also is system dependent. On UNIX systems, a pathname is absolute if its prefix is "/". On Microsoft Windows systems, a pathname is absolute if its prefix is a drive specifier followed by "\\", or if its prefix is "\\\\".

The canonical pathname is absolute pathname without redunant names such as "." and "..".

The java.nio.file package defines interfaces and classes for the Java virtual machine to access files, file attributes, and file systems. This API may be used to overcome many of the limitations of the File class. Most useful in package are Path and Files.

You can use streams to read from or write to files.

// Read file located in a directory "mydir" relative 
// to the current working directory and is UTF-8 encoded.
Path path = FileSystems.getDefault()
    .getPath("mydir", "myfile.txt");

try(BufferedReader reader = Files.newBufferedReader(
               path, 
               StandardCharsets.UTF_8)){
...               
}
// deep directory traverse try (Stream<Path> paths = Files.walk(Paths.get("mydir"))) { paths.forEach((path)->{ // ... do something }); } catch (IOException e) { e.printStackTrace(); }

More examples

File

constructor description
File(parent, pathname) Creates a new File instance with file name pathname in parent folder. Parent can be specified by File object or as string with path.
File(pathname) Creates a new File instance with given pathname.
File(uri) Creates a new File instance by converting uri to abstract pathname.
method description
canExecute() Tests whether the application can execute this file.
canRead() Tests whether the application can read this file.
canWrite() Tests whether the application can modify this file.
exists() Tests whether the file exists.
isAbsolute() Tests whether this pathname is absolute.
isDirectory() Tests whether this is a directory.
isFile() Tests whether this file is a normal file.
isHidden() Tests whether this file is a hidden file.
getAbsoluteFile() Returns file with the absolute form of pathname.
getAbsolutePath() Returns the absolute pathname string.
getCanonicalFile() Returns file with the canonical form of pathname.
getCanonicalPath() Returns the canonical pathname string.
getName() Returns the name of the file (tail of pathname).
getPath() Returns the pahname string.
getParentFile() Returns the parent pathname or null if this pathname does not name a parent directory.
getParent() Returns the parent pathname string or null if this pathname does not name a parent directory.
lastModified() Returns the time in ms when file was last modified.
length() Returns the length of this file in bytes.
getTotalSpace() Returns the size of the partition named by this pathname in bytes or 0L if this pathname does not name a partition.
getUsableSpace()

Returns the number of available bytes on the partition or 0L if this pathname does not name a partition. On systems where this information is not available, this method will be equivalent to a call to getFreeSpace().

When possible, this method checks for write permissions and other operating system restrictions and will therefore usually provide a more accurate estimate of how much new data can actually be written than getFreeSpace().

getFreeSpace() Returns the number of unallocated bytes in the partition or 0L if this pathname does not name a partition.
compareTo(file) Compares pathnames of this file and given file.
equals(obj) Tests this pathname for equality with the given object.
createNewFile() Creates a new, empty file named by this pathname if and only if a file does not yet exist.
delete() Deletes this file. Returns true if and only if the file or directory is successfully deleted, and false otherwise.
deleteOnExit() Requests that this file must be deleted when the virtual machine terminates.
list() Returns an array of strings naming the files and directories in this directory.
list(fileNameFilter) Returns an array of strings naming the files and directories in this directory, that satisfy the specified filter.
listFiles() Returns an array of files and directories in this directory.
listFiles(fileFilter) Returns an array of files and directories in this directory that satisfy the specified filter.
listFiles(fileNameFilter) Returns an array of files and directories in this directory that satisfy the specified filter.
static
property description
pathSeparator The system-dependent path-separator character, represented as a string for convenience.
pathSeparatorChar The system-dependent path-separator character. On UNIX systems, this character is ':'; on Microsoft Windows systems it is ';'.
separatorChar The system-dependent default name-separator character. On UNIX systems the value of this field is '/'; on Microsoft Windows systems it is '\\'.
separator The system-dependent default name-separator character, represented as a string for convenience. This string contains a single character, namely separatorChar property.
method description
createTempFile(pref, suff) Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.
createTempFile(pref, suff, dir) Creates an empty file in the specified directory, using the given prefix and suffix to generate its name.
listRoots()

Return array of files denoting the available filesystem roots, or null if the set of roots could not be determined. UNIX platforms have a single root directory, namely "/", Windows platforms have a root directory for each active drive.

The set of available filesystem roots is affected by various system-level operations such as the insertion or ejection of removable media and the disconnecting or unmounting of physical or virtual disk drives.

Path

A Path represents a path that is hierarchical and composed of a sequence of directory and file name elements separated by a special separator or delimiter. A root component, that identifies a file system hierarchy, may also be present.

This interface extends Watchable interface so that a directory located by a path can be registered with a WatchService and entries in the directory watched.

There is util class Paths, that allows create the Path objects from string and URI.

method description
getFileName() Returns the name of the file or directory denoted by this path as a Path object.
getName(ind) Returns a name element of this path as a Path object.
getNameCount() Returns the number of name elements in the path.
getParent() Returns the parent path, or null if this path does not have a parent.
getRoot() Returns the root component of this path as a Path object, or null if this path does not have a root component.
getFileSystem() Returns the file system that created this object.
startsWith(path) Tests if this path starts with the given path.
endsWith(path) Tests if this path ends with the given path.
isAbsolute() Tells whether or not this path is absolute.
iterator() Returns an iterator over the name elements of this path.
normalize() Returns a path that is this path with redundant name elements eliminated.
relativize(path) Constructs a relative path between this path and a given path.
resolve(strpath) Converts a given path string to a Path and resolves it against this Path.
resolve(path) Resolve the given path against this path.
resolveSibling(strpath) Converts a given path string to a Path and resolves it against this path's parent path.
resolveSibling(path) Resolves the given path against this path's parent path.
subpath(indBegin, indEnd) Returns a relative Path that is a subsequence of the name elements of this path.
register(watcher, events) Registers the file located by this path with a watch service.
register(watcher, events, modifiers) Registers the file located by this path with a watch service.
hashCode() Computes a hash code for this path.
equals(obj) Tests this path for equality with the given object.
compareTo(path) Compares two abstract paths lexicographically.
toAbsolutePath() Returns a Path object representing the absolute path of this path.
toRealPath(linkopt) Returns the real path of an existing file.
toFile() Returns a File object representing this path.
toString() Returns the string representation of this path.
toUri() Returns a URI to represent this path.