Welcome

首页 / 软件开发 / JAVA / 检查与创建目录

检查与创建目录2007-05-28 yycnet.yeah.net yyc译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 ...
" +"Creates each path
" +"Usage:MakeDirectories -d path1 ...
" +"Deletes each path
" +"Usage:MakeDirectories -r path1 path2
" +"Renames from path1 to path2
";private static void usage() {System.err.println(usage);System.exit(1);}private static void fileData(File f) {System.out.println("Absolute path: " + f.getAbsolutePath() +"
 Can read: " + f.canRead() +"
 Can write: " + f.canWrite() +"
 getName: " + f.getName() +"
 getParent: " + f.getParent() +"
 getPath: " + f.getPath() +"
 length: " + f.length() +"
 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 existif(!del) {f.mkdirs();System.out.println("created " + f);}}fileData(f);}}} ///:~
在fileData()中,可看到应用了各种文件调查方法来显示与文件或目录路径有关的信息。
main()应用的第一个方法是renameTo(),利用它可以重命名(或移动)一个文件至一个全新的路径(该路径由参数决定),它属于另一个File对象。这也适用于任何长度的目录。
若试验上述程序,就可发现自己能制作任意复杂程度的一个目录路径,因为mkdirs()会帮我们完成所有工作。在Java 1.0中,-d标志报告目录虽然已被删除,但它依然存在;但在Java 1.1中,目录会被实际删除。