Objective
- use the File class in Java
The File class
- The File class is used to find out details about a file or directory.
- Although it can be used to create a file, the name of the class is somewhat
misleading - it is more like a DirectoryEntry than a File.
- Need to use: import java.io.File;
- See the documentation for the File class.
- See the FileInfo.java demonstration program (included below):
/*
FileInfo.java
CIS 260
David Klick
2009-01-20
This program demonstrates the use of the File
class to find out information about a file.
*/
import java.io.File;
import java.util.Scanner;
import java.util.Date;
public class FileInfo {
public static void main(String[] args) {
String strIn; // holder for user input
// open keyboard input and get file/path spec from user
Scanner kbd = new Scanner(System.in);
System.out.print("Enter path of file to examine (QUIT to exit): ");
strIn = kbd.nextLine();
while (!strIn.equalsIgnoreCase("QUIT")) {
// create new File object
File f = new File(strIn);
// display file information
if (!f.exists()) {
System.out.println(strIn + " does not exist");
} else {
StringBuffer s = new StringBuffer();
if (f.isFile()) s.append(f.getName() + " is a file\n");
if (f.isDirectory()) s.append(strIn + " is a directory\n");
if (!f.isAbsolute()) {
s.append(strIn + " is not an absolute path\n" +
"The absolute path is " + f.getAbsolutePath() + "\n");
} else {
s.append(strIn + " is an absolute path\n");
}
s.append(strIn + " is " + (f.canRead()?"":"not ") + "readable\n");
s.append(strIn + " is " + (f.canWrite()?"":"not ") + "writeable\n");
if (f.isFile()) s.append("The length is " + f.length() + "\n");
Date d = new Date(f.lastModified());
s.append(strIn + " was last modified on " + d + "\n");
if (f.isDirectory()) {
String[] files = f.list();
s.append("\nThe files in this directory are:\n");
for (String str : files) s.append(str + '\n');
}
System.out.println(s);
}
// ask for next file/path spec
System.out.print("Enter path of file to examine (QUIT to exit): ");
strIn = kbd.nextLine();
}
}
}