File類有兩個構造方法,File(父目錄,文件名),關聯指定的目錄下指定名稱的文件,File(文件名/目錄名),關聯某個文件名或者目錄,這里的/表示的意思是“或者”。
比較好的方法是先用一個File對象關聯一個目錄名,然后創建這個目錄,(mkdir()),再用構造方法構造一個文件。以下的代碼是在“我的文檔”里創建一個名為“1.txt”的文件。
File dir=new File("C:"+File.separator+"Documents and Settings"+File.separator+"Yxy"+File.separator+"My Documents"); //此處注意轉義字符
dir.mkdir(); //創建目錄
File file1=new File(dir,"1.txt");
file1.createNewFile(); //創建一個新文件
String[] str1=dir.list(); //下文說到的list()
//不知道為什么這里的空格硬是只能這么長,代碼是我從我自己的代碼里拷過來的,汗
//一個先
各位,其實這里可以用轉義字符“\\”來代替File.separator,但是這不是一個好的習慣。為了實現Java的一次編譯,四處運行的性感特點,我們需要一個通用的文件分隔符,因為各種操作系統下存在差異,比如linux的文件分隔符是正斜杠"/"。而File的特性separator正是獲取當前操作系統下的文件分隔符。另,千萬不要將讓"\"單獨存在,在代碼中這是一個轉義字符的標識,它會將接下來的一個字符理解為轉義字符。
除了這種方法可以創建新的文件,還可以調用File類下的一個靜態函數
File createTempFile(String prefix,String suffix,File directory),這是一個完整的版本,在指定的目錄下創建一個以prefix為前綴名,suffix為后綴名的臨時文件,通過deleteOnExit()來刪除。但是還有一個精簡的版本,
File createTempFile(String prefix,String suffix),沒有指定目錄,將在當前操作系統默認的臨時文件夾里創建以prefix為前綴名,suffix為后綴名的臨時文件。
以上是如何創建文件,接下來講的是如何查閱目錄下的文件和通過文件過濾器查找文件。
看到前面的代碼里寫到的list()方法了嗎,返回一個String類型的數組,獲取當前目錄下的所有文件名,包括目錄名(即文件夾)。但是,這樣是不夠的,無法找到我們所需要的文件,我們需要的是按我們的要求找到某個房間。Java.io包類提供類文件過濾器FileNameFilter,它是一個接口,內有方法boolean accept(File dir, String name),這是一個需要重寫的方法,重寫了這個方法之后,list(FileNameFileter f)方法可以列出符合我們要求的方法。
本文來源【學網】網站鏈接是http://www.xue5.com
Java中的separator,pathSeparator等常量- -
File.separatorChar 返回一個字符,表示當前系統默認的文件名分隔符,在Windows中為"\",unix中為"/"。
File.separator 與前者相同,但將分隔符作為字符串類型返回。
pathSeparatorChar 返回一個字符,表示當前系統默認的路徑名分隔符,在Windows中為";",unix中為":"。
File.pathSeparator 與前者相同,但將分隔符作為字符串類型返回。
正文為JDKAPI幫助文檔相關內容:
separatorChar
public static final char separatorCharThe system-dependent default name-separator character. This field is initialized to contain the first character of the value of the system property file.separator. On UNIX systems the value of this field is '/'; on Microsoft Windows systems it is '\'.
See Also:
System.getProperty(java.lang.String)
--------------------------------------------------------------------------------
separator
public static final String separatorThe system-dependent default name-separator character, represented as a string for convenience. This string contains a single character, namely separatorChar.
--------------------------------------------------------------------------------
pathSeparatorChar
public static final char pathSeparatorCharThe system-dependent path-separator character. This field is initialized to contain the first character of the value of the system property path.separator. This character is used to separate filenames in a sequence of files given as a path list. On UNIX systems, this character is ':'; on Microsoft Windows systems it is ';'.
See Also:
System.getProperty(java.lang.String)
--------------------------------------------------------------------------------
pathSeparator
public static final String pathSeparatorThe system-dependent path-separator character, represented as a string for convenience. This string contains a single character, namely pathSeparatorChar.