简体   繁体   English

Java中如何检查目录中是否存在文件

[英]How to Check if a File Exists in a Directory in Java

I would like to find out if a particular directory has a file in it already in Java, specifically I need to check if the file exists in a given directory using Java code.我想知道某个特定目录是否已经在 Java 中有一个文件,特别是我需要使用 Java 代码检查该文件是否存在于给定目录中。

However, I need the code to not crash and burn due to the various permissions / file rights and how it can be used.但是,由于各种权限/文件权限以及如何使用它,我需要代码不会崩溃和烧毁。 It's going in a cross platform app.它正在跨平台应用程序中进行。 I've seen the question checking if file exists in a specific directory this isn't what I'm needing however.我已经看到了检查文件是否存在于特定目录中的问题,但这不是我需要的。

Any kind soles with some clean Java code ideas.. (sorry if my English is bad I'm not American).任何带有一些干净 Java 代码想法的鞋底..(对不起,如果我的英语不好,我不是美国人)。

Update: Found what I needed eventually https://javajudo.com/how-to-check-if-a-file-exists-in-a-directory-in-java/更新:找到了我最终需要的 https://javajudo.com/how-to-check-if-a-file-exists-in-a-directory-in-java/

Thanks, for the help.谢谢您的帮助。

You can test whether a file or directory exists using the Java File exists() method.您可以使用 Java File exists()方法测试文件或目录是否存在。

File file = new File("/temp.txt");
boolean cond1 = file.exists();

The method will return true when the file or directory is found and false if the file is not found.当找到文件或目录时,该方法将返回 true,如果未找到文件,则返回 false。

You can also use the Files.exists() and Files.notExists() Java methods if that is easier too.如果这也更容易,您还可以使用Files.exists()Files.notExists() Java 方法。

There are also the constants Constants.FILE_EXISTS and Constants.FILE_EXISTS you can use to test conditions.还有常量Constants.FILE_EXISTSConstants.FILE_EXISTS可用于测试条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM