I'm using the following code to get an array with all sub directories from a given path.
我正在使用以下代码来获取包含给定路径中所有子目录的数组。
String[] subDirs = path.split(File.separator);
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.
我需要数组来检查某些文件夹是否在此路径中的正确位置。这看起来是一个很好的解决方案,直到findBugs抱怨File.separator用作正则表达式。似乎将Windows文件分隔符传递给正在构建正则表达式的函数是一个坏主意,因为反斜杠是一个转义字符。
How can I split the path in a cross platform way without using File.separator? Or is code like this okay?
如何在不使用File.separator的情况下以跨平台方式拆分路径?或者这样的代码好吗?
String[] subDirs = path.split("/");
6 个解决方案
#1
14
Use path.getParentFile()
repeatedly to get all components of a path.
重复使用path.getParentFile()获取路径的所有组件。
Discouraged way would be to
path.replaceAll("\\", "/").split("/")
.
气馁的方式是path.replaceAll(“\\”,“/”)。split(“/”)。
#2
36
Literalizing pattern strings
Whenever you need to literalize an arbitraryString
to be used as a regex pattern, use Pattern.quote
:
每当您需要将任意字符串文字化以用作正则表达式模式时,请使用Pattern.quote:
From the API:
来自API:
public static String quote(String s)
public static String quote(String s)
Returns a literal pattern
String
for the specifiedString
. This method produces aString
that can be used to create aPattern
that would match the strings
as if it were a literal pattern. Metacharacters or escape sequences in the input sequence will be given no special meaning.返回指定String的文字模式String。此方法生成一个String,该String可用于创建与字符串s匹配的Pattern,就好像它是文字模式一样。输入序列中的元字符或转义序列将没有特殊含义。
Parameters:
s
- The string to be literalized
Returns: A literal string replacement参数:s - 要文字化的字符串返回:文字字符串替换
This means that you can do the following:
这意味着您可以执行以下操作:
String[] subDirs = path.split(Pattern.quote(File.separator));
Literalizing replacement strings
If you need to literalize an arbitrary replacement String
, use Matcher.quoteReplacement
.
如果需要对任意替换String进行字面化,请使用Matcher.quoteReplacement。
From the API:
来自API:
public static String quoteReplacement(String s)
public static String quoteReplacement(String s)
Returns a literal replacement
String
for the specifiedString
. This method produces aString
that will work as a literal replacements
in theappendReplacement
method of theMatcher
class. TheString
produced will match the sequence of characters ins
treated as a literal sequence. Slashes ('\'
) and dollar signs ('$'
) will be given no special meaning.返回指定String的文字替换String。此方法生成一个String,它将作为Matcher类的appendReplacement方法中的文字替换。生成的String将匹配s中作为文字序列处理的字符序列。斜杠('\')和美元符号('$')将没有特殊含义。
Parameters:
s
- The string to be literalized
Returns: A literal string replacement参数:s - 要文字化的字符串返回:文字字符串替换
This quoted replacement String
is also useful in String.replaceFirst
and String.replaceAll
:
这个引用的替换String在String.replaceFirst和String.replaceAll中也很有用:
Note that backslashes (
\
) and dollar signs ($
) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. UseMatcher.quoteReplacement
to suppress the special meaning of these characters, if desired.请注意,替换字符串中的反斜杠(\)和美元符号($)可能会导致结果与将其视为文字替换字符串时的结果不同。如果需要,使用Matcher.quoteReplacement来抑制这些字符的特殊含义。
Examples
System.out.println(
"O.M.G.".replaceAll(".", "!")
); // prints "!!!!!!"
System.out.println(
"O.M.G.".replaceAll(Pattern.quote("."), "!")
); // prints "O!M!G!"
System.out.println(
"Microsoft software".replaceAll("so", "$0")
); // prints "Microsoft software"
System.out.println(
"Microsoft software".replaceAll("so", Matcher.quoteReplacement("$0"))
); // prints "Micro$0ft $0ftware"
#3
1
java.nio.file.Path implements Iterable<Path>
, so you can do:
java.nio.file.Path实现了Iterable
public static void showElements(Path p) {
List<String> nameElements = new ArrayList<>();
for (Path nameElement: p)
nameElements.add(nameElement.toFile().getName());
System.out.printf("For this file: [%s], the following elements were found: [%s]\n"
, p.toAbsolutePath()
, Joiner.on(", ").join(nameElements));
}
Methods getNameCount and getName can be used for a similar purpose.
方法getNameCount和getName可用于类似目的。
#4
0
You can use Path interface:
您可以使用Path接口:
Path p = Paths.get(pathStr);
for (int i = 0; i < p.getNameCount(); i++) {
String name = p.getName(i).toString();
//do what you need with name;
}
#5
0
Create an empty list and use forEach to iterate over the path elements inserting each one into the list for later use:
创建一个空列表并使用forEach迭代路径元素,将每个元素插入列表*以后使用:
List<String> pathElements = new ArrayList<>();
Paths.get("/foo/bar/blah/baz").forEach(p -> pathElements.add(p.toString()))
Also, if you need a specific path element use:
此外,如果您需要特定的路径元素,请使用:
<pathObject>.getName(<intIndex>).toString()
where <pathObject>
is returned by a call to Paths.get()
, and if you need multiple parts of the path returned in a string use:
其中
<pathObject>.subPath(<intStart>, <intEnd>).toString()
You can get the total number of path elements (for use in <intEnd>
) with:
您可以使用以下命令获取路径元素的总数(在
<pathObject>.getNameCount()
There are other useful methods at the Java Path and Paths doc pages.
Java Path和Paths文档页面还有其他有用的方法。
#6
-2
What about
关于什么
String[] subDirs = path.split(File.separator.replaceAll("\\", "\\\\"));
#1
14
Use path.getParentFile()
repeatedly to get all components of a path.
重复使用path.getParentFile()获取路径的所有组件。
Discouraged way would be to
path.replaceAll("\\", "/").split("/")
.
气馁的方式是path.replaceAll(“\\”,“/”)。split(“/”)。
#2
36
Literalizing pattern strings
Whenever you need to literalize an arbitraryString
to be used as a regex pattern, use Pattern.quote
:
每当您需要将任意字符串文字化以用作正则表达式模式时,请使用Pattern.quote:
From the API:
来自API:
public static String quote(String s)
public static String quote(String s)
Returns a literal pattern
String
for the specifiedString
. This method produces aString
that can be used to create aPattern
that would match the strings
as if it were a literal pattern. Metacharacters or escape sequences in the input sequence will be given no special meaning.返回指定String的文字模式String。此方法生成一个String,该String可用于创建与字符串s匹配的Pattern,就好像它是文字模式一样。输入序列中的元字符或转义序列将没有特殊含义。
Parameters:
s
- The string to be literalized
Returns: A literal string replacement参数:s - 要文字化的字符串返回:文字字符串替换
This means that you can do the following:
这意味着您可以执行以下操作:
String[] subDirs = path.split(Pattern.quote(File.separator));
Literalizing replacement strings
If you need to literalize an arbitrary replacement String
, use Matcher.quoteReplacement
.
如果需要对任意替换String进行字面化,请使用Matcher.quoteReplacement。
From the API:
来自API:
public static String quoteReplacement(String s)
public static String quoteReplacement(String s)
Returns a literal replacement
String
for the specifiedString
. This method produces aString
that will work as a literal replacements
in theappendReplacement
method of theMatcher
class. TheString
produced will match the sequence of characters ins
treated as a literal sequence. Slashes ('\'
) and dollar signs ('$'
) will be given no special meaning.返回指定String的文字替换String。此方法生成一个String,它将作为Matcher类的appendReplacement方法中的文字替换。生成的String将匹配s中作为文字序列处理的字符序列。斜杠('\')和美元符号('$')将没有特殊含义。
Parameters:
s
- The string to be literalized
Returns: A literal string replacement参数:s - 要文字化的字符串返回:文字字符串替换
This quoted replacement String
is also useful in String.replaceFirst
and String.replaceAll
:
这个引用的替换String在String.replaceFirst和String.replaceAll中也很有用:
Note that backslashes (
\
) and dollar signs ($
) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. UseMatcher.quoteReplacement
to suppress the special meaning of these characters, if desired.请注意,替换字符串中的反斜杠(\)和美元符号($)可能会导致结果与将其视为文字替换字符串时的结果不同。如果需要,使用Matcher.quoteReplacement来抑制这些字符的特殊含义。
Examples
System.out.println(
"O.M.G.".replaceAll(".", "!")
); // prints "!!!!!!"
System.out.println(
"O.M.G.".replaceAll(Pattern.quote("."), "!")
); // prints "O!M!G!"
System.out.println(
"Microsoft software".replaceAll("so", "$0")
); // prints "Microsoft software"
System.out.println(
"Microsoft software".replaceAll("so", Matcher.quoteReplacement("$0"))
); // prints "Micro$0ft $0ftware"
#3
1
java.nio.file.Path implements Iterable<Path>
, so you can do:
java.nio.file.Path实现了Iterable
public static void showElements(Path p) {
List<String> nameElements = new ArrayList<>();
for (Path nameElement: p)
nameElements.add(nameElement.toFile().getName());
System.out.printf("For this file: [%s], the following elements were found: [%s]\n"
, p.toAbsolutePath()
, Joiner.on(", ").join(nameElements));
}
Methods getNameCount and getName can be used for a similar purpose.
方法getNameCount和getName可用于类似目的。
#4
0
You can use Path interface:
您可以使用Path接口:
Path p = Paths.get(pathStr);
for (int i = 0; i < p.getNameCount(); i++) {
String name = p.getName(i).toString();
//do what you need with name;
}
#5
0
Create an empty list and use forEach to iterate over the path elements inserting each one into the list for later use:
创建一个空列表并使用forEach迭代路径元素,将每个元素插入列表*以后使用:
List<String> pathElements = new ArrayList<>();
Paths.get("/foo/bar/blah/baz").forEach(p -> pathElements.add(p.toString()))
Also, if you need a specific path element use:
此外,如果您需要特定的路径元素,请使用:
<pathObject>.getName(<intIndex>).toString()
where <pathObject>
is returned by a call to Paths.get()
, and if you need multiple parts of the path returned in a string use:
其中
<pathObject>.subPath(<intStart>, <intEnd>).toString()
You can get the total number of path elements (for use in <intEnd>
) with:
您可以使用以下命令获取路径元素的总数(在
<pathObject>.getNameCount()
There are other useful methods at the Java Path and Paths doc pages.
Java Path和Paths文档页面还有其他有用的方法。
#6
-2
What about
关于什么
String[] subDirs = path.split(File.separator.replaceAll("\\", "\\\\"));