Check if Dir exists in Windows/Unix using Java

huangapple go评论93阅读模式
英文:

Check if Dir exists in Windows/Unix using Java

问题

在Unix中,只读取'/'作为文件夹结构的分隔符,而Windows则同时接受'\'和'/'。是否有一种方法可以在Java中检查两者都存在的文件夹是否存在?
如果文件夹结构中包含'\',并且我们使用'f.isDirectory()',Unix将无法读取文件夹结构。
提前感谢。

英文:

Since Unix reads only '/' for folder structure and windows takes both '\' ,'/' .Is there a way to check if dir exists for both in Java?
if folder structure has '\' and we use --> 'f.isDirectory()' , the Unix doesn't read the folder structure.
Thanks in advance.

答案1

得分: 1

你可以考虑使用java.nio.file中的Path API:

Path rootDirectory = Path.of(System.getProperty("user.home")); // 假设为 /home/noobie
Path subDirectory = rootDirectory.resolve("sub"); // home/noobie/sub
Path subSubDirectory = subDirectory.resolve("subsub"); // /home/noobie/sub/subsub
Path subSubDirectoryMethod2 = rootDirectory.resolve("sub").resolve("subsub"); // /home/noobie/sub/subsub

无论在哪个平台上,这个API都可以工作。要检查路径是否是目录,你可以使用以下代码:

boolean isDir = Files.isDirectory(path);
英文:

You could look into using the Path API from java.nio.file:

Path rootDirectory = Path.of(System.getProperty("user.home")); // Let's say /home/noobie
Path subDirectory = rootDirectory.resolve("sub"); // home/noobie/sub
Path subSubDirectory = subDirectory.resolve("subsub"); // /home/noobie/sub/subsub
Path subSubDirectoryMethod2 = rootDirectory.resolve("sub").resolve("subsub"); // /home/noobie/sub/subsub

This API works regardless of platform. To check if a path is a directory you can do:

boolean isDir = Files.isDirectory(path);

答案2

得分: 0

我找到了这篇帖子,它提到了Linux和Windows之间的区别,以及如何使用File.separator进行修复。

https://stackoverflow.com/questions/5971964/file-separator-or-file-pathseparator

英文:

I found this post, it mentions the difference between Linux and Windows and how to fix it with File.seperator

https://stackoverflow.com/questions/5971964/file-separator-or-file-pathseparator

huangapple
  • 本文由 发表于 2020年7月28日 14:02:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/63127956.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定