Java NIO file path issue

Solution 1:

You need to convert the found resource to URI. It works on all platforms and protects you from possible errors with paths. You must not worry about how full path looks like, whether it starts with '\' or other symbols. If you think about such details - you do something wrong.

ClassLoader classloader = Thread.currentThread().getContextClassLoader();
String platformIndependentPath = Paths.get(classloader.getResource(errorFile).toURI()).toString();

Solution 2:

The path \C:\Sample\sample.txt must not have a leading \. It should be just C:\Sample\sample.txt

Solution 3:

To make it work on both Windows and Linux\OS X consider doing this:

String osAppropriatePath = System.getProperty( "os.name" ).contains( "indow" ) ? filePath.substring(1) : filePath;

If you want to worry about performance I'd store System.getProperty( "os.name" ).contains( "indow" ) as a constant like

private static final boolean IS_WINDOWS = System.getProperty( "os.name" ).contains( "indow" );

and then use:

String osAppropriatePath = IS_WINDOWS ? filePath.substring(1) : filePath;