創(chuàng)建文件
我們可以從中創(chuàng)建一個(gè)?File?
對(duì)象
- 路徑名
- 父路徑名和子路徑名
- URI(統(tǒng)一資源標(biāo)識(shí)符)
我們可以使用File類(lèi)的以下構(gòu)造函數(shù)之一創(chuàng)建一個(gè)文件:
File(String pathname)
File(File parent, String child)
File(String parent, String child)
File(URI uri)
如果我們有一個(gè)文件路徑名字符串test.txt,我們可以創(chuàng)建一個(gè)抽象路徑名作為下面的代碼。
File dummyFile = new File("test.txt");
名為test.txt的文件不必存在,以使用此語(yǔ)句創(chuàng)建File對(duì)象。
dummyFile對(duì)象表示抽象路徑名,它可能指向或可能不指向文件系統(tǒng)中的真實(shí)文件。
File類(lèi)有幾個(gè)方法來(lái)處理文件和目錄。
使用File對(duì)象,我們可以創(chuàng)建新文件,刪除現(xiàn)有文件,重命名文件,更改文件的權(quán)限等。
File類(lèi)中的isFile()和isDirectory()告訴File對(duì)象是否表示文件或目錄。
當(dāng)前工作目錄
JVM的當(dāng)前工作目錄是根據(jù)我們?nèi)绾芜\(yùn)行java命令來(lái)設(shè)置的。
我們可以通過(guò)讀取user.dir系統(tǒng)屬性來(lái)獲取JVM的當(dāng)前工作目錄,如下所示:
String workingDir = System.getProperty("user.dir");
使用System.setProperty()方法更改當(dāng)前工作目錄。
System.setProperty("user.dir", "C:\\myDir");
要在Windows上指定C:\\ test作為user.dir系統(tǒng)屬性值,我們運(yùn)行如下所示的程序:
java -Duser.dir=C:\test your-java-class
文件的存在
我們可以使用File類(lèi)的exists()方法檢查File對(duì)象的抽象路徑名是否存在。
boolean fileExists = dummyFile.exists();
完整源代碼
import java.io.File;
public class Main {
public static void main(String[] argv) {
// Create a File object
File dummyFile = new File("dummy.txt");
// Check for the file"s existence
boolean fileExists = dummyFile.exists();
if (fileExists) {
System.out.println("The dummy.txt file exists.");
} else {
System.out.println("The dummy.txt file does not exist.");
}
}
}
上面的代碼生成以下結(jié)果。
路徑
絕對(duì)路徑在文件系統(tǒng)上唯一標(biāo)識(shí)文件。規(guī)范路徑是唯一標(biāo)識(shí)文件系統(tǒng)上文件的最簡(jiǎn)單路徑。
我們可以使用getAbsolutePath()和getCanonicalPath()方法來(lái)分別獲得由File對(duì)象表示的絕對(duì)路徑和規(guī)范路徑。
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
printFilePath("dummy.txt");
printFilePath(".." + File.separator + "notes.txt");
}
public static void printFilePath(String pathname) {
File f = new File(pathname);
System.out.println("File Name: " + f.getName());
System.out.println("File exists: " + f.exists());
System.out.println("Absolute Path: " + f.getAbsolutePath());
try {
System.out.println("Canonical Path: " + f.getCanonicalPath());
}
catch (IOException e) {
e.printStackTrace();
}
}
}
上面的代碼生成以下結(jié)果。
文件分隔符
不同的操作系統(tǒng)使用不同的字符來(lái)分隔路徑名中的兩個(gè)部分。
例如,Windows在路徑名中使用反斜杠(\)作為名稱(chēng)分隔符,而UNIX使用正斜杠(/)。
File類(lèi)定義了一個(gè)名為分隔符Char的常量,它是系統(tǒng)相關(guān)的名稱(chēng)分隔符。
我們可以使用File.separator Char常量來(lái)獲取名稱(chēng)分隔符作為字符。
File.separator?
常量將我們的名稱(chēng)分隔符作為String。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-745827.html
在程序中使用名稱(chēng)分隔符將使您的Java代碼在不同的平臺(tái)上工作。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-745827.html
到了這里,關(guān)于Java IO教程- Java文件的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!