如何独立分割路径平台? [英] How to split a path platform independent?
问题描述
我正在使用以下代码从给定路径获取包含所有子目录的数组。
I'm using the following code to get an array with all sub directories from a given path.
String[] subDirs = path.split(File.separator);
我需要数组来检查某些文件夹是否在此路径中的正确位置。
这看起来是一个很好的解决方案,直到findBugs抱怨File.separator用作正则表达式。似乎将Windows文件分隔符传递给正在构建正则表达式的函数是一个坏主意,因为反斜杠是一个转义字符。
I need the array to check if certain folders are at the right place in this path. This looked like a good solution until findBugs complains that File.separator is used as a regular expression. It seems that passing the windows file separator to a function that is building a regex from it is a bad idea because the backslash being an escape character.
如何在不使用File.separator的情况下以跨平台方式拆分路径?
或者这样的代码好吗?
How can I split the path in a cross platform way without using File.separator? Or is code like this okay?
String[] subDirs = path.split("/");
推荐答案
使用 path.getParentFile( )
反复获取路径的所有组件。
Use path.getParentFile()
repeatedly to get all components of a path.
气馁的方式是 path.replaceAll( \\,/)。split(/)
。
Discouraged way would be to path.replaceAll("\\", "/").split("/")
.
这篇关于如何独立分割路径平台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!