简体   繁体   中英

String utils split - linux

Below Java code works in Windows machine

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. if loop is not executing, else loop is executing.

Do we need to give split as "\\" or "/" for 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.

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

The JavaDoc says ( 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 '\\'.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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