Thursday, October 1, 2009

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.

Align Left
Constructors
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.
public static constants
s = File.separator;Default path separator (eg, "/" in Unix, "\" in Windows).
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.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.
b = f.setReadOnly();Make file read only. Returns true if successful.
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 /'s. Directory paths end with /.
s = f.toURI();path with "file:" prefix and /'s. Directory paths end with /.
Creating and deleting files and directories
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.
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.


0 comments:

Post a Comment