我們先來看完整的代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
import java.io.File; public class JudgeFile { public static void main(String[] args) { File dir = new File( "D:/" ); //聲明D磁盤 boolean d=dir.exists(); boolean f=file.exists(); if (d== true ){ System.out.println(dir.getAbsolutePath()+ "目錄存在" ); } else { System.out.println(dir.getAbsolutePath()+ "目錄不存在" ); } if (f== true ){ System.out.println(file.getAbsolutePath()+ "文件存在" ); } else { System.out.println(file.getAbsolutePath()+ "文件不存在" ); } } } |
說明:
exists() 方法來檢測文件或目錄是否存在
getAbsolutePath()方法打印磁盤路徑
如果不聲明目錄,例如File file = new File(“test”); 默認路徑為java項目夾的路徑
原文鏈接:https://www.idaobin.com/archives/748.html