Java 如何独立地拆分路径平台?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1099859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:44:57  来源:igfitidea点击:

How to split a path platform independent?

javaregexfilecross-platform

提问by Janusz

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("/"); 

采纳答案by akarnokd

Use path.getParentFile()repeatedly to get all components of a path.

path.getParentFile()重复使用以获取路径的所有组件。

Discouraged way would be to path.replaceAll("\\", "/").split("/").

气馁的方法是path.replaceAll("\\", "/").split("/")

回答by Michael

What about

关于什么

String[] subDirs = path.split(File.separator.replaceAll("\", "\\"));

回答by polygenelubricants

Literalizing pattern strings

文字化模式字符串

Whenever you need to literalize an arbitraryStringto be used as a regex pattern, use Pattern.quote:

每当您需要将任意String一个用作正则表达式模式时,请使用Pattern.quote

From the API:

从API:

public static String quote(String s)

Returns a literal pattern Stringfor the specified String. This method produces a Stringthat can be used to create a Patternthat would match the string sas if it were a literal pattern. Metacharacters or escape sequences in the input sequence will be given no special meaning.

Parameters:s- The string to be literalized
Returns:A literal string replacement

public static String quote(String s)

返回String指定的文字模式String。此方法生成String可用于创建Pattern匹配字符串的a ,就s好像它是文字模式一样。输入序列中的元字符或转义序列将没有特殊含义。

参数: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)

Returns a literal replacement Stringfor the specified String. This method produces a Stringthat will work as a literal replacement sin the appendReplacementmethod of the Matcherclass. The Stringproduced will match the sequence of characters in streated as a literal sequence. Slashes ('\') and dollar signs ('$') will be given no special meaning.

Parameters:s- The string to be literalized
Returns:A literal string replacement

public static String quoteReplacement(String s)

返回String指定的文字替换String。这种方法产生一个String,将工作作为文字置换sappendReplacement所述的方法Matcher的类。该String产生了的字符序列将匹配s视为文字序列。斜线 ( '\') 和美元符号 ( '$') 没有特殊含义。

参数:s- 要文字化的字符串
返回:文字字符串替换

This quoted replacement Stringis also useful in String.replaceFirstand String.replaceAll:

这个引用的替换StringString.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. Use Matcher.quoteReplacementto 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", "
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));
}
") ); // prints "Microsoft software" System.out.println( "Microsoft software".replaceAll("so", Matcher.quoteReplacement("
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;
}
")) ); // prints "Micro
List<String> pathElements = new ArrayList<>();
Paths.get("/foo/bar/blah/baz").forEach(p -> pathElements.add(p.toString()))
ft
<pathObject>.getName(<intIndex>).toString() 
ftware"

回答by Marcus Junius Brutus

java.nio.file.Pathimplements Iterable<Path>, so you can do:

java.nio.file.Path实现Iterable<Path>,所以你可以这样做:

<pathObject>.subPath(<intStart>, <intEnd>).toString()

Methods getNameCountand getNamecan be used for a similar purpose.

方法getNameCountgetName可用于类似目的。

回答by alniks

You can use Path interface:

您可以使用 Path 接口:

<pathObject>.getNameCount()

回答by sabujp

Create an empty list and use forEach to iterate over the path elements inserting each one into the list for later use:

创建一个空列表并使用 forEach 迭代路径元素,将每个元素插入列表以供以后使用:

##代码##

Also, if you need a specific path element use:

此外,如果您需要特定的路径元素,请使用:

##代码##

where <pathObject>is returned by a call to Paths.get(), and if you need multiple parts of the path returned in a string use:

where<pathObject>由调用返回Paths.get(),如果您需要在字符串中返回路径的多个部分,请使用:

##代码##

You can get the total number of path elements (for use in <intEnd>) with:

您可以通过以下方式获取路径元素的总数(用于<intEnd>):

##代码##

There are other useful methods at the Java Pathand Pathsdoc pages.

Java PathPaths文档页面上还有其他有用的方法。