Home Java Java-tips Io 10file java.io.File

Ask Questions?

View Latest Questions



Posted on: July 26, 2006 at 12:00 AM
java.io.File is the central class in working with files and directories.

Java Notes


java.io.File is the central class in working with files and directories.

Files and directories are both represented by File objects.

There are many methods available in java.io.File class. It can be used to manipulate the file object in many ways.

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.

fnew File(path);Create File object for default directory (usually where program is located).
fnew File(dirpath, fname);Create File object for directory path given as string.
fnew File(dir, fname);Create File object for directory.
public static constants
sFile.separator;Default path separator (eg, "/" in Unix, "\" in Windows).
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.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.
bf.setReadOnly();Make file read only. Returns true if successful.
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 /'s. Directory paths end with /.
sf.toURI();path with "file:" prefix and /'s. Directory paths end with /.
Creating and deleting files and directories
bf.delete();Deletes the file.
bf.createNewFile();Create file, may throw IOException. true if OK; 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.
Copyleft 2005 Fred Swartz MIT License