javastringsplitstring-utils

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


Solution

  • 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]