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
fnew File(path);Create File object.
fnew File(dirpath, filename);Create File object.
fnew File(dir, filename);Create File object.
Getting Attributes
bf.exists();true if file exists.
bf.isFile();true if this is a normal file.
bf.isDirectory();true if f is a directory.
sf.getName();name of file or directory.
bf.canRead();true if can read file.
bf.canWrite();true if can write file.
bf.setReadOnly();Make file read only.
bf.isHidden();true if file is hidden.
lf.lastModified();Time of last modification.
lf.length();Number of bytes in file.
Setting Attributes
 f.setLastModified(t);Sets last modified time to long value t.
Paths
sf.getPath();path name.
sf.getAbsolutePath();path name (how is it different from above?).
sf.getCanonicalPath();path name. May throw IOException.
sf.toURL();path with "file:" prefix and forward slashes. Directory paths will end with slash.
sf.toURI();path with "file:" prefix and forward slashes. Directory paths will end with slash.
Creating and deleting files and directories
bf.delete();Deletes the file.
bf.createNewFile();Creates file, may throw IOException. true if successful; false if already exists.
bf.renameTo(f2);Renames f to File f2. Returns true if successful.
bf.mkdir();Creates a directory. Returns true if successful.
bf.mkdirs();Creates directory and all dirs in path. Returns true if successful.
Parents and Children
sf.getParent();Name of parent directory.
dirf.getParentFile();File of parent.
sadir.list();Array of file/directory names in dir.
fadir.listFiles();Array of files/directories in dir.
fadir.listFiles(ff);As above after applying java.io.FileFilter ff.