字符串实用程序拆分 - linux
String utils split - linux
下面的 Java 代码在 Windows 机器上工作
filepath = "euro\football\france\winners.txt";
String[] values = StringUtils.split(filePath, "\");
if (values != null && values.length >= 4) {
} else {
//error
}
但在执行代码时遇到 linux 中的问题。 if 循环没有执行,else 循环正在执行。
linux
是否需要将拆分为“\”或“/”
String[] values = StringUtils.split(filePath, "\");
任何建议都会有所帮助
为了避免这种情况,我会使用简单的正则表达式 [/\]
,它将与 /
或 \
分开,像这样:
String[] filePaths = {
"euro/football/france/winners.txt", //linux path
"euro\football\france\winners.txt" //windows path
};
for (String filePath : filePaths) {
String[] values = filePath.split("[/\\]");
System.out.println(Arrays.toString(values));
}
产出
[euro, football, france, winners.txt]
[euro, football, france, winners.txt]
如果文件在 JVM 为 运行 的机器上,那么您可以使用 File.separatorChar
获取本地机器的系统相关分隔符。
String[] values = StringUtils.split(filePath, File.separator);
JavaDoc 表示 (File.separatorChar
):
The system-dependent default name-separator character. This field is
initialized to contain the first character of the value of the system
property file.separator. On UNIX systems the value of this field is
'/'; on Microsoft Windows systems it is '\'.
下面的 Java 代码在 Windows 机器上工作
filepath = "euro\football\france\winners.txt";
String[] values = StringUtils.split(filePath, "\");
if (values != null && values.length >= 4) {
} else {
//error
}
但在执行代码时遇到 linux 中的问题。 if 循环没有执行,else 循环正在执行。
linux
是否需要将拆分为“\”或“/”String[] values = StringUtils.split(filePath, "\");
任何建议都会有所帮助
为了避免这种情况,我会使用简单的正则表达式 [/\]
,它将与 /
或 \
分开,像这样:
String[] filePaths = {
"euro/football/france/winners.txt", //linux path
"euro\football\france\winners.txt" //windows path
};
for (String filePath : filePaths) {
String[] values = filePath.split("[/\\]");
System.out.println(Arrays.toString(values));
}
产出
[euro, football, france, winners.txt]
[euro, football, france, winners.txt]
如果文件在 JVM 为 运行 的机器上,那么您可以使用 File.separatorChar
获取本地机器的系统相关分隔符。
String[] values = StringUtils.split(filePath, File.separator);
JavaDoc 表示 (File.separatorChar
):
The system-dependent default name-separator character. This field is initialized to contain the first character of the value of the system property file.separator. On UNIX systems the value of this field is '/'; on Microsoft Windows systems it is '\'.