使用Java查找文件

use*_*237 2 java

我是第一次使用File类,我有点困惑.

我写了这个基本代码,看看我的桌面上是否有文件被检测到:

public static void main(String[]args){
    File test= new File("abc.pdf");
    if(test.exists()==true){
        System.out.println("got it!");
    }
    else{System.out.println("try again");}
}
Run Code Online (Sandbox Code Playgroud)

我知道我错过了一大步,因为程序似乎无法检测到它.谁能告诉我还有什么我需要查询的?谢谢.

avi*_*iad 6

您需要指定绝对路径.例如:

File file = new File("C:\\abcfolder\\abc.pdf");
Run Code Online (Sandbox Code Playgroud)

为了获得桌面绝对路径:

String desktopPath = WindowsUtils.getCurrentUserDesktopPath();
Run Code Online (Sandbox Code Playgroud)

然后:

File file = new File(desktopPath+"\\abc.pdf");
Run Code Online (Sandbox Code Playgroud)