Check here and read about java.io package.
Constructing a Filename Path
A File object is used to represent a filename. Creating the File object has no effect on the file system; the filename need not exist nor is it created.
On Windows, this example creates the path \a\b. On Unix, the path would be /a/b.
String path = File.separator + “a” + File.separator + “b”;
Converting Between a Filename Path and a URL// Create a file object
File file = new File(“filename”);
// Convert the file object to a URL
URL url = null;
try {
// The file need not exist. It is made into an absolute path
// by prefixing the current working directory
url = file.toURL(); // file:/d:/almanac1.4/java.io/filename
} catch (MalformedURLException e) {
}
// Convert the URL to a file object
file = new File(url.getFile()); // d:/almanac1.4/java.io/filename
// Read the file contents using the URL
try {
// Open an input stream
InputStream is = url.openStream();
// Read from is
is.close();
} catch (IOException e) {
// Could not open the file
}
Getting an Absolute Filename Path from a Relative Filename PathFile file = new File(“filename.txt”);
file = file.getAbsoluteFile(); // c:\temp\filename.txt
file = new File(“dir”+File.separatorChar+”filename.txt”);
file = file.getAbsoluteFile(); // c:\temp\dir\filename.txt
file = new File(“..”+File.separatorChar+”filename.txt”);
file = file.getAbsoluteFile(); // c:\temp\..\filename.txt
// Note that filename.txt does not need to exist
Determining If Two Filename Paths Refer to the Same FileA filename path may include redundant names such as `.’ or `..’ or symbolic links (on UNIX platforms). File.getCanonicalFile() converts a filename path to a unique canonical form suitable for comparisons.
File file1 = new File(“./filename”);
File file2 = new File(“filename”);
// Filename paths are not equal
boolean b = file1.equals(file2); // false
// Normalize the paths
try {
file1 = file1.getCanonicalFile(); // c:\almanac1.4\filename
file2 = file2.getCanonicalFile(); // c:\almanac1.4\filename
} catch (IOException e) {
}
// Filename paths are now equal
b = file1.equals(file2); // true
Getting the Parents of a Filename Path// Get the parent of a relative filename path
File file = new File(“Ex1.java”);
String parentPath = file.getParent(); // null
File parentDir = file.getParentFile(); // null
// Get the parents of an absolute filename path
file = new File(“D:\\alm\\Ex1.java”);
parentPath = file.getParent(); // D:\alm
parentDir = file.getParentFile(); // D:\alm
parentPath = parentDir.getParent(); // D:\
parentDir = parentDir.getParentFile(); // D:\
parentPath = parentDir.getParent(); // null
parentDir = parentDir.getParentFile(); // null
Determining If a Filename Path Is a File or a DirectoryFile dir = new File(“directoryName”);
boolean isDir = dir.isDirectory();
if (isDir) {
// dir is a directory
} else {
// dir is a file
}
Creating a Filetry {
File file = new File(“filename”);
// Create file if it does not exist
boolean success = file.createNewFile();
if (success) {
// File did not exist and was created
} else {
// File already exists
}
} catch (IOException e) {
}
Getting the Size of a FileFile file = new File(“infilename”);
// Get the number of bytes in the file
long length = file.length();
Deleting a File
boolean success = (new File(“filename”)).delete();
if (!success) {
// Deletion failed
}
Renaming a File or Directory// File (or directory) with old name
File file = new File(“oldname”);
// File (or directory) with new name
File file2 = new File(“newname”);
// Rename file (or directory)
boolean success = file.renameTo(file2);
if (!success) {
// File was not successfully renamed
}
Moving a File or Directory to Another Directory// File (or directory) to be moved
File file = new File(“filename”);
// Destination directory
File dir = new File(“directoryname”);
// Move file to new directory
boolean success = file.renameTo(new File(dir, file.getName()));
if (!success) {
// File was not successfully moved
}
Getting and Setting the Modification Time of a File or DirectoryThis example gets the last modified time of a file or directory and then sets it to the current time.
File file = new File(“filename”);
// Get the last modified time
long modifiedTime = file.lastModified();
// 0L is returned if the file does not exist
// Set the last modified time
long newModifiedTime = System.currentTimeMillis();
boolean success = file.setLastModified(newModifiedTime);
if (!success) {
// operation failed.
}
DirectoryThe working directory is the location in the file system from where the java command was invoked.
String curDir = System.getProperty(“user.dir”);
- Creating a Directory
// Create a directory; all ancestor directories must exist
boolean success = (new File(“directoryName”)).mkdir();
if (!success) {
// Directory creation failed
}
// Create a directory; all non-existent ancestor directories are
// automatically created
success = (new File(“directoryName”)).mkdirs();
if (!success) {
// Directory creation failed
}
- Deleting a Directory
// Delete an empty directory
boolean success = (new File(“directoryName”)).delete();
if (!success) {
// Deletion failed
}
If the directory is not empty, it is necessary to first recursively delete all files and subdirectories in the directory. Here is a method that will delete a non-empty directory.
// Deletes all files and subdirectories under dir.
// Returns true if all deletions were successful.
// If a deletion fails, the method stops attempting to delete and returns false.
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
- Listing the Files or Subdirectories in a Directory
This example lists the files and subdirectories in a directory. To list all descendant files and subdirectories under a directory, see e33 Traversing the Files and Directories Under a Directory.
File dir = new File(“directoryName”);
String[] children = dir.list();
if (children == null) {
// Either dir does not exist or is not a directory
} else {
for (int i=0; i<children.length; i++) {
// Get filename of file or directory
String filename = children[i];
}
}
// It is also possible to filter the list of returned files.
// This example does not return any files that start with `.’.
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return !name.startsWith(“.”);
}
};
children = dir.list(filter);
// The list of files can also be retrieved as File objects
File[] files = dir.listFiles();
// This filter only returns directories
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);
- Listing the File System Roots
UNIX file systems have a single root, `/’. On Windows, each drive is a root. For example the C drive is represented by the root C:\.
File[] roots = File.listRoots();
for (int i=0; i<roots.length; i++) {
process(roots[i]);
}
- Traversing the Files and Directories Under a Directory
This example implements methods that recursively visits all files and directories under a directory.
// Process all files and directories under dir
public static void visitAllDirsAndFiles(File dir) {
process(dir);
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
visitAllDirsAndFiles(new File(dir, children[i]));
}
}
}
// Process only directories under dir
public static void visitAllDirs(File dir) {
if (dir.isDirectory()) {
process(dir);
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
visitAllDirs(new File(dir, children[i]));
}
}
}
// Process only files under dir
public static void visitAllFiles(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
visitAllFiles(new File(dir, children[i]));
}
} else {
process(dir);
}
}