更新時(shí)間:2022-06-13 10:58:47 來源:動(dòng)力節(jié)點(diǎn) 瀏覽1613次
在本教程中,動(dòng)力節(jié)點(diǎn)小編將進(jìn)行Java File類概述,它是java.io API 的一部分。 File類使我們能夠處理文件系統(tǒng)上的文件和目錄。
File 類 有 4 個(gè)公共構(gòu)造函數(shù)。根據(jù)開發(fā)者的需要,可以創(chuàng)建不同類型的File類實(shí)例。
File(String pathname) – 創(chuàng)建一個(gè)代表給定路徑名的實(shí)例
File(String parent, String child) – 創(chuàng)建一個(gè)實(shí)例,表示通過連接 父路徑和 子路徑形成的路徑
File(File parent, String child) – 創(chuàng)建一個(gè)實(shí)例,其路徑由另一個(gè) File 實(shí)例表示的父路徑和子路徑連接而成
File(URI uri) – 創(chuàng)建一個(gè)代表給定統(tǒng)一資源標(biāo)識(shí)符的實(shí)例
File類 有許多方法允許我們使用和操作文件系統(tǒng)上的文件。我們將在這里重點(diǎn)介紹其中的一些。重要的是要注意File類不能修改或訪問它所代表的文件的內(nèi)容。
(1)創(chuàng)建和刪除目錄和文件
File類具有創(chuàng)建和刪除目錄和文件的 實(shí)例方法。目錄和文件分別使用mkdir和createNewFile方法創(chuàng)建。
使用 刪除方法刪除目錄和文件。所有這些方法都返回一個(gè)布爾值,當(dāng)操作成功時(shí)為真,否則為假:
@Test
public void givenDir_whenMkdir_thenDirIsDeleted() {
File directory = new File("dir");
assertTrue(directory.mkdir());
assertTrue(directory.delete());
}
@Test
public void givenFile_whenCreateNewFile_thenFileIsDeleted() {
File file = new File("file.txt");
try {
assertTrue(file.createNewFile());
} catch (IOException e) {
fail("Could not create " + "file.txt");
}
assertTrue(file.delete());
}
在上面的代碼片段中,我們還看到了其他有用的方法。
isDirectory方法可用于測(cè)試提供的名稱表示的文件是否為目錄,而isFile方法可用于測(cè)試提供的名稱表示的文件是否為文件。并且,我們可以使用exists方法 來測(cè)試一個(gè)目錄或文件是否已經(jīng)存在于系統(tǒng)中。
(2)獲取有關(guān)文件實(shí)例的元數(shù)據(jù)
File 類有許多返回有關(guān)File 實(shí)例的元數(shù)據(jù)的 方法。讓我們看看如何使用getName、getParentFile和 getPath方法:
@Test
public void givenFile_whenCreateNewFile_thenMetadataIsCorrect() {
String sep = File.separator;
File parentDir = makeDir("filesDir");
File child = new File(parentDir, "file.txt");
try {
child.createNewFile();
} catch (IOException e) {
fail("Could not create " + "file.txt");
}
assertEquals("file.txt", child.getName());
assertEquals(parentDir.getName(), child.getParentFile().getName());
assertEquals(parentDir.getPath() + sep + "file.txt", child.getPath());
removeDir(parentDir);
}
在這里,我們演示了驗(yàn)證有關(guān)在目錄中創(chuàng)建的文件的元數(shù)據(jù)。我們還展示了如何找到文件的父級(jí)以及該文件的相對(duì)路徑。
(3)設(shè)置文件和目錄權(quán)限
File 類具有允許您設(shè)置文件或目錄權(quán)限的方法。 在這里,我們將看看setWritable和setReadable 方法:
@Test
public void givenReadOnlyFile_whenCreateNewFile_thenCantModFile() {
File parentDir = makeDir("readDir");
File child = new File(parentDir, "file.txt");
try {
child.createNewFile();
} catch (IOException e) {
fail("Could not create " + "file.txt");
}
child.setWritable(false);
boolean writable = true;
try (FileOutputStream fos = new FileOutputStream(child)) {
fos.write("Hello World".getBytes()); // write operation
fos.flush();
} catch (IOException e) {
writable = false;
} finally {
removeDir(parentDir);
}
assertFalse(writable);
}
在上面的代碼中,我們?cè)陲@式設(shè)置阻止任何寫入的權(quán)限后嘗試寫入文件。我們使用setWritable方法來做到這一點(diǎn)。不允許在寫入文件時(shí)嘗試寫入文件會(huì)導(dǎo)致拋出IOException。
接下來,我們?cè)谠O(shè)置阻止任何讀取的權(quán)限后嘗試從文件中讀取。使用setReadable方法阻止讀取:
@Test
public void givenWriteOnlyFile_whenCreateNewFile_thenCantReadFile() {
File parentDir = makeDir("writeDir");
File child = new File(parentDir, "file.txt");
try {
child.createNewFile();
} catch (IOException e) {
fail("Could not create " + "file.txt");
}
child.setReadable(false);
boolean readable = true;
try (FileInputStream fis = new FileInputStream(child)) {
fis.read(); // read operation
} catch (IOException e) {
readable = false;
} finally {
removeDir(parentDir);
}
assertFalse(readable);
}
同樣,JVM 將在嘗試讀取不允許讀取的文件時(shí)拋出IOException。
(4)列出目錄中的文件
File 類具有允許我們列出目錄中包含的文件的方法。 同樣,也可以列出目錄。在這里,我們將看看list和 list(FilenameFilter)方法:
@Test
public void givenFilesInDir_whenCreateNewFile_thenCanListFiles() {
File parentDir = makeDir("filtersDir");
String[] files = {"file1.csv", "file2.txt"};
for (String file : files) {
try {
new File(parentDir, file).createNewFile();
} catch (IOException e) {
fail("Could not create " + file);
}
}
//normal listing
assertEquals(2, parentDir.list().length);
//filtered listing
FilenameFilter csvFilter = (dir, ext) -> ext.endsWith(".csv");
assertEquals(1, parentDir.list(csvFilter).length);
removeDir(parentDir);
}
我們創(chuàng)建了一個(gè)目錄并向其中添加了兩個(gè)文件——一個(gè)帶有csv 擴(kuò)展名,另一個(gè)帶有 txt 擴(kuò)展名。當(dāng)列出目錄中的所有文件時(shí),我們得到了預(yù)期的兩個(gè)文件。當(dāng)我們通過過濾帶有csv擴(kuò)展名的文件來過濾列表時(shí),我們只返回一個(gè)文件。
(5)重命名文件和目錄
File類具有使用renameTo 方法重命名文件和目錄的 功能:
@Test
public void givenDir_whenMkdir_thenCanRenameDir() {
File source = makeDir("source");
File destination = makeDir("destination");
boolean renamed = source.renameTo(destination);
if (renamed) {
assertFalse(source.isDirectory());
assertTrue(destination.isDirectory());
removeDir(destination);
}
}
在上面的示例中,我們創(chuàng)建了兩個(gè)目錄——源目錄和目標(biāo)目錄。然后我們使用renameTo方法將源目錄重命名為目標(biāo)目錄。同樣可以用來重命名文件而不是目錄。
(6)獲取磁盤空間信息
File 類 還允許我們獲取磁盤空間信息。讓我們看一下getFreeSpace方法的演示:
@Test
public void givenDataWritten_whenWrite_thenFreeSpaceReduces() {
String home = System.getProperty("user.home");
String sep = File.separator;
File testDir = makeDir(home + sep + "test");
File sample = new File(testDir, "sample.txt");
long freeSpaceBefore = testDir.getFreeSpace();
try {
writeSampleDataToFile(sample);
} catch (IOException e) {
fail("Could not write to " + "sample.txt");
}
long freeSpaceAfter = testDir.getFreeSpace();
assertTrue(freeSpaceAfter < freeSpaceBefore);
removeDir(testDir);
}
在此示例中,我們?cè)谟脩舻闹髂夸浿袆?chuàng)建了一個(gè)目錄,然后在其中創(chuàng)建了一個(gè)文件。然后我們檢查了在用一些文本填充這個(gè)文件后主目錄分區(qū)上的可用空間是否發(fā)生了變化。提供有關(guān)磁盤空間信息的其他方法是getTotalSpace和 getUsableSpace。如果大家想了解更多相關(guān)知識(shí),可以關(guān)注一下動(dòng)力節(jié)點(diǎn)的Java基礎(chǔ)教程,里面有更豐富的知識(shí)等著大家去學(xué)習(xí),希望對(duì)大家能夠有所幫助。
相關(guān)閱讀
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問老師會(huì)電話與您溝通安排學(xué)習(xí)
初級(jí) 202925
初級(jí) 203221
初級(jí) 202629
初級(jí) 203743