Skip to content
Advertisement

Get error when trying to split file path in Java

System.out.println(p)

For the above code, I get the following output where p is a Path object.

C:repoUnit-test-coverageabcdunit-test-repopcmbbsourcepcmbbdatabaseWorkOrderTenderUtil.plsql

I want to get the file name without extension. So I tried the below code.

System.out.println(p.getFileName().toString());

Then I got the following output.

WorkOrderTenderUtil.plsql

To get the filename without extension what I tried to split the above output by .. But splitting is not happening as expected. Always the length of the resulting array is 0.

What is the reason for this. What I am doing wrong. I tried to get the file name by the following workaround as well. But getting the same error.

new File(p).getName().split(".");

Advertisement

Answer

The split method takes a regular expression as its parameter. “.” is a special token that matches any character and therefore matches all the characters in the string, leaving nothing left to return.

You will need to escape the period with two backslashes to have the regular expression target only the period.

"WorkOrderTenderUtil.plsql".split("\.");

This returns an array of length 2 with values of “WorkOrderTenderUtil” and “plsql”

Advertisement