简体   繁体   English

String utils split - linux

[英]String utils split - linux

Below Java code works in Windows machine 以下Java代码适用于Windows机器

filepath = "euro\football\france\winners.txt";
String[] values = StringUtils.split(filePath, "\\");

if (values != null && values.length >= 4) {

} else {
    //error
}

But facing issue in linux while executing the code. 但是在执行代码时面临linux中的问题。 if loop is not executing, else loop is executing. 如果循环没有执行,则执行其他循环。

Do we need to give split as "\\" or "/" for linux 我们是否需要为Linux分配“\\”或“/”

String[] values = StringUtils.split(filePath, "\\");

Any suggestion will be helpful 任何建议都会有所帮助

If the file is on the machine the JVM is running then you can use File.separatorChar to get the system-dependend separator of the local machine. 如果文件在JVM正在运行的计算机上,则可以使用File.separatorChar获取本地计算机的系统依赖分隔符。

    String[] values = StringUtils.split(filePath, File.separator);

The JavaDoc says ( File.separatorChar ): 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. 此字段初始化为包含系统属性file.separator的值的第一个字符。 On UNIX systems the value of this field is '/'; 在UNIX系统上,该字段的值为“/”; on Microsoft Windows systems it is '\\'. 在Microsoft Windows系统上它是'\\'。

To avoid that I would use simple regex [/\\\\] which will split either with / or \\ , like this : 为了避免这种情况,我会使用简单的正则表达式[/\\\\] ,它将与/\\分开,如下所示:

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));
}

Outputs 输出

[euro, football, france, winners.txt]
[euro, football, france, winners.txt]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM