File類並不僅僅是對現有目錄路徑、文件或者文件組的一個表示。亦可用一個File對象新建一個目錄,甚至創建一個完整的目錄路徑——假如它尚不存在的話。亦可用它了解文件的屬性(長度、上一次修改日期、讀/寫屬性等),檢查一個File對象到底代表一個文件還是一個目錄,以及刪除一個文件等等。下列程序完整展示了如何運用File類剩下的這些方法:
//: MakeDirectories.java
// Demonstrates the use of the File class to
// create directories and manipulate files.
import java.io.*;
public class MakeDirectories {
private final static String usage =
"Usage:MakeDirectories path1 ...\n" +
"Creates each path\n" +
"Usage:MakeDirectories -d path1 ...\n" +
"Deletes each path\n" +
"Usage:MakeDirectories -r path1 path2\n" +
"Renames from path1 to path2\n";
private static void usage() {
System.err.println(usage);
System.exit(1);
}
private static void fileData(File f) {
System.out.println(
"Absolute path: " + f.getAbsolutePath() +
"\n Can read: " + f.canRead() +
"\n Can write: " + f.canWrite() +
"\n getName: " + f.getName() +
"\n getParent: " + f.getParent() +
"\n getPath: " + f.getPath() +
"\n length: " + f.length() +
"\n lastModified: " + f.lastModified());
if(f.isFile())
System.out.println("it's a file");
else if(f.isDirectory())
System.out.println("it's a directory");
}
public static void main(String[] args) {
if(args.length < 1) usage();
if(args[0].equals("-r")) {
if(args.length != 3) usage();
File
old = new File(args[1]),
rname = new File(args[2]);
old.renameTo(rname);
fileData(old);
fileData(rname);
return; // Exit main
}
int count = 0;
boolean del = false;
if(args[0].equals("-d")) {
count++;
del = true;
}
for( ; count < args.length; count++) {
File f = new File(args[count]);
if(f.exists()) {
System.out.println(f + " exists");
if(del) {
System.out.println("deleting..." + f);
f.delete();
}
}
else { // Doesn't exist
if(!del) {
f.mkdirs();
System.out.println("created " + f);
}
}
fileData(f);
}
}
} ///:~
在fileData()中,可看到應用了各種文件調查方法來顯示與文件或目錄路徑有關的信息。
main()應用的第一個方法是renameTo(),利用它可以重命名(或移動)一個文件至一個全新的路徑(該路徑由參數決定),它屬於另一個File對象。這也適用於任何長度的目錄。
若試驗上述程序,就可發現自己能制作任意復雜程度的一個目錄路徑,因為mkdirs()會幫我們完成所有工作。在Java 1.0中,-d標志報告目錄雖然已被刪除,但它依然存在;但在Java 1.1中,目錄會被實際刪除。