英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论