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 fname; // File name
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.
f = | new File(path); | Create File object for default directory (usually where program is located). |
f = | new File(dirpath, fname); | Create File object for directory path given as string. |
f = | new File(dir, fname); | Create File object for directory. |
s = | File.separator; | Default path separator (eg, "/" in Unix, "\" in Windows). |
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.isHidden(); | true if file is hidden. |
l = | f.lastModified(); | Time of last modification. |
l = | f.length(); | Number of bytes in file. |
| f.setLastModified(t); | Sets last modified time to long value t. |
b = | f.setReadOnly(); | Make file read only. Returns true if successful. |
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 /'s. Directory paths end with /. |
s = | f.toURI(); | path with "file:" prefix and /'s. Directory paths end with /. |
b = | f.delete(); | Deletes the file. |
b = | f.createNewFile(); | Create file, may throw IOException.
true if OK; 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. |
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. |