Java 不知道文件何时不存在

发布于 2024-11-05 16:58:06 字数 381 浏览 2 评论 0原文

Java知道文件何时存在,因为它会打印出“文件已找到”,但是当文件不存在时,它不会打印“文件未找到”,

    File file = new File(filePath, "Test_1.exe");

    if (file.exists()){
        System.out.println("File found");
    }else{
        System.out.println("File not found");
    }

有人知道为什么吗?文件路径是正确的,因为我已经仔细检查了这一点。只是奇怪的是,如果文件不存在,则不会打印出来,但如果存在,则会打印出来。

我也尝试过 if (!file.exists()) 但不走运!

Java knows when a file exists as it prints out "File found" but when the file does not exists it does NOT print "File not found"

    File file = new File(filePath, "Test_1.exe");

    if (file.exists()){
        System.out.println("File found");
    }else{
        System.out.println("File not found");
    }

does any one know why? the file path is correct as I have double checked this. Just weird that if the file does not exists it wont print out but will if it does.

I have also tried if (!file.exists()) with not luck!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

始于初秋 2024-11-12 16:58:06

尝试

try
{
    File file = new File(filePath, "Test_1.exe");

     if (file.exists())
     {
          System.out.println("File found");
     }
     else
     {
            System.out.println("File not found");
      }
}
catch(SecurityException se)
{
     se.printStackTrace();
}

Try

try
{
    File file = new File(filePath, "Test_1.exe");

     if (file.exists())
     {
          System.out.println("File found");
     }
     else
     {
            System.out.println("File not found");
      }
}
catch(SecurityException se)
{
     se.printStackTrace();
}
丢了幸福的猪 2024-11-12 16:58:06

尝试使用文件的完整路径。例如:

File file = new File(filePath, "c:/temp/Test_1.exe");

来自javadocs:

相反,相对路径名必须根据从其他路径名获取的信息进行解释。默认情况下,java.io 包中的类始终根据当前用户目录解析相对路径名。该目录由系统属性 user.dir 命名,通常是调用 Java 虚拟机的目录。

Try using the full path to the file. eg :

File file = new File(filePath, "c:/temp/Test_1.exe");

From the javadocs :

A relative pathname, in contrast, must be interpreted in terms of information taken from some other pathname. By default the classes in the java.io package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir, and is typically the directory in which the Java virtual machine was invoked.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文