Java: java.io.File

java.io.File is the central class in working with files and directories. Files and directories are both represented by File objects. When a File object is created, the system doesn't test to see if a corresponding file/directory actually exists; you must call exists() to check. See Example - FileTest.java.

File Constructors and Methods

Assume
boolean b;
String s;
String path;     // Relative or absolute path.
String dirpath;  // Relative or absolute path to a directory.
String filename;
File   f, dir;   // Assume f is a file, dir is a directory.
long   l;
File[] fa;      // Array of File objects.
String[] sa;    // Array of file or directory names.
Constructors
f = new File(path);Create File object.
f = new File(dirpath, filename);Create File object.
f = new File(dir, filename);Create File object.
Getting Attributes
b = f.exists();true if file exists.
b = f.isFile();true if this is a normal file.
b = f.isDirectory();true if f is a directory.
s = f.getName();name of file or directory.
b = f.canRead();true if can read file.
b = f.canWrite();true if can write file.
b = f.setReadOnly();Make file read only.
b = f.isHidden();true if file is hidden.
l = f.lastModified();Time of last modification.
l = f.length();Number of bytes in file.
Setting Attributes
 f.setLastModified(t);Sets last modified time to long value t.
Paths
s = f.getPath();path name.
s = f.getAbsolutePath();path name (how is it different from above?).
s = f.getCanonicalPath();path name. May throw IOException.
s = f.toURL();path with "file:" prefix and forward slashes. Directory paths will end with slash.
s = f.toURI();path with "file:" prefix and forward slashes. Directory paths will end with slash.
Creating and deleting files and directories
b = f.delete();Deletes the file.
b = f.createNewFile();Creates file, may throw IOException. true if successful; false if already exists.
b = f.renameTo(f2);Renames f to File f2. Returns true if successful.
b = f.mkdir();Creates a directory. Returns true if successful.
b = f.mkdirs();Creates directory and all dirs in path. Returns true if successful.
Parents and Children
s = f.getParent();Name of parent directory.
dir = f.getParentFile();File of parent.
sa = dir.list();Array of file/directory names in dir.
fa = dir.listFiles();Array of files/directories in dir.
fa = dir.listFiles(ff);As above after applying java.io.FileFilter ff.