我正在使用新的Java 7 IO功能,实际上我试图接收文件夹的所有xml文件.但是当文件夹不存在时会引发异常,如何检查该文件夹是否与新IO一起存在?
public UpdateHandler(String release) {
log.info("searching for configuration files in folder " + release);
Path releaseFolder = Paths.get(release);
try(DirectoryStream<Path> stream = Files.newDirectoryStream(releaseFolder, "*.xml")){
for (Path entry: stream){
log.info("working on file " + entry.getFileName());
}
}
catch (IOException e){
log.error("error while retrieving update configuration files " + e.getMessage());
}
}
Run Code Online (Sandbox Code Playgroud)
Jes*_*per 241
使用java.nio.file.Files
:
Path path = ...;
if (Files.exists(path)) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
您可以选择传递此方法LinkOption
值:
if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
Run Code Online (Sandbox Code Playgroud)
还有一种方法notExists
:
if (Files.notExists(path)) {
Run Code Online (Sandbox Code Playgroud)
Chr*_*per 193
非常简单:
new File("/Path/To/File/or/Directory").exists();
Run Code Online (Sandbox Code Playgroud)
如果你想确定它是一个目录:
File f = new File("/Path/To/File/or/Directory");
if (f.exists() && f.isDirectory()) {
...
}
Run Code Online (Sandbox Code Playgroud)
Fer*_*eia 48
要检查新IO是否存在目录:
if (Files.isDirectory(Paths.get("directory"))) {
...
}
Run Code Online (Sandbox Code Playgroud)
isDirectory
true
如果文件是目录则返回; false
如果文件不存在,不是目录,或者无法确定文件是否是目录.
请参阅:文档.
您需要将Path转换为a File
并测试存在:
for(Path entry: stream){
if(entry.toFile().exists()){
log.info("working on file " + entry.getFileName());
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
从文件夹目录的字符串生成文件
String path="Folder directory";
File file = new File(path);
Run Code Online (Sandbox Code Playgroud)
和使用方法存在。
如果要生成文件夹,请使用mkdir()
if (!file.exists()) {
System.out.print("No Folder");
file.mkdir();
System.out.print("Folder created");
}
Run Code Online (Sandbox Code Playgroud)
小智 5
import java.io.File;
import java.nio.file.Paths;
public class Test
{
public static void main(String[] args)
{
File file = new File("C:\\Temp");
System.out.println("File Folder Exist" + isFileDirectoryExists(file));
System.out.println("Directory Exists" + isDirectoryExists("C:\\Temp"));
}
public static boolean isFileDirectoryExists(File file)
{
if (file.exists())
{
return true;
}
return false;
}
public static boolean isDirectoryExists(String directoryPath)
{
if (!Paths.get(directoryPath).toFile().isDirectory())
{
return false;
}
return true;
}
}
Run Code Online (Sandbox Code Playgroud)