Reputation: 963
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
Upvotes: 1
Views: 255
Reputation: 5173
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 '\'.
Upvotes: 2
Reputation: 59960
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]
Upvotes: 1