9.4 文件
在我們進行文件操作時, 需要知道關(guān)于文件的信息。File類提到了成員函數(shù)來操縱文件和獲得文件的信息。
9.4.1 創(chuàng)建一個新的文件對象
你可用下面三個方法來創(chuàng)建一個新文件對象:
File myFile; myFile = new File("etc/motd");
或
myFile = new File("/etc","motd");
//more useful if the directory or filename are variables
或
File myDir = new file("/etc");
myFile = new File(myDir,"motd");
這三種方法取決于你訪問文件的方式。例如,如果你在應(yīng)用程序里只用一個文 件,第一種創(chuàng)建文件的結(jié)構(gòu)是最容易的。 但如果你在同一目錄里打開數(shù)個文件, 則第二種或第三種結(jié)構(gòu)更好。
9.4.2 文件測試和使用
創(chuàng)建了一個文件對象, 你便可以使用以下成員函數(shù)來獲得文件相關(guān)信息:
文件名:String getName() , 路徑:String getPath() 絕對路徑:String getAbslutePath() ;重命名:boolean renameTo(File newName) 。
文件測試:boolean exists(),boolean canWrite(),boolean canRead() ,boolean isFile() ,boolean isDirectory() ,boolean isAbsolute()。
一般文件信息:long lastModified() ,long length()。
目錄用法:boolean mkdir() ,String[] list()!
9.4.3 文件信息獲取例子程序
這里是一個獨立的顯示文件的基本信息的程序,文件通過命令行參數(shù)傳輸:
import java.io.*;
class fileInfo{
File fileToCheck;
public static void main(String args[]) throws IOException{
if (args.length>0){
for (int i=0;i fileToCheck = new File(args[i]);
info(fileToCheck);
}
}
else{
System.out.println("No file given.");
}
}
public void info (File f) throws IOException{
System.out.println("Name: "+f.getName());
System.out.println("Path: "=f.getPath());
if (f.exists()) {
System.out.println("File exists.");
System.out.print((f.canRead() ?" and is Readable":""));
System.out.print((f.cnaWrite()?" and is Writeable":""));
System.out.println(".");
System.out.println("File is " + f.lenght() = " bytes.");
}
else {
System.out.println("File does not exist.");
}
}
}