在 Java 中檢查檔案是否存在\n
java.io.File 類提供有關檔案的有用方法。此示例演示如何使用 File 類中的 file.exists() 方法檢查檔案是否存在。
示例
import java.io.File;
public class Main {
public static void main(String[] args) {
File file = new File("C:/java.txt");
System.out.println(file.exists());
}
}結果
如果“java.txt”檔案存在於“C”驅動器中,則上述程式碼示例將生成以下結果。
true
示例
以下是 Java 中關於檔案是否存在的另一個簡單示例。
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintpWriter;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class fileexist {
public static void main(String[] args) throws IOException {
File f = new File(System.getProperty("user.dir")+"/folder/file.txt");
System.out.println(f.exists());
if(!f.getParentFile().exists()) {
f.getParentFile().mkdirs();
}
if(!f.exists()) {
try {
f.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
File dir = new File(f.getParentFile(), f.getName());
PrintpWriter pWriter = new PrintpWriter(dir);
pWriter.print("writing anything...");
pWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}輸出
如果“java.txt”檔案存在於“C”驅動器中,則上述程式碼示例將生成以下結果。
true
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP