我使用以下代码来获取路径
Path errorFilePath = FileSystems.getDefault().getPath(errorFile);
Run Code Online (Sandbox Code Playgroud)
当我尝试使用File NIO移动文件时,我收到以下错误:
java.nio.file.InvalidPathException: Illegal char <:> at index 2: \C:\Sample\sample.txt
Run Code Online (Sandbox Code Playgroud)
我也试过使用URL.encode(errorFile)哪个导致同样的错误.
Ale*_*ndr 33
您需要将找到的资源转换为URI.它适用于所有平台,并保护您免受路径可能出现的错误.您不必担心完整路径的样子,无论是以'\'还是其他符号开头.如果你考虑这些细节 - 你做错了什么.
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
String platformIndependentPath = Paths.get(classloader.getResource(errorFile).toURI()).toString();
Run Code Online (Sandbox Code Playgroud)
Sle*_*led 18
为了使它适用于Windows和Linux\OS X,请考虑这样做:
String osAppropriatePath = System.getProperty( "os.name" ).contains( "indow" ) ? filePath.substring(1) : filePath;
Run Code Online (Sandbox Code Playgroud)
如果你想担心性能,我会把它存储System.getProperty( "os.name" ).contains( "indow" )为常数
private static final boolean IS_WINDOWS = System.getProperty( "os.name" ).contains( "indow" );
Run Code Online (Sandbox Code Playgroud)
然后使用:
String osAppropriatePath = IS_WINDOWS ? filePath.substring(1) : filePath;
Run Code Online (Sandbox Code Playgroud)
Eri*_*ric 15
为了确保在任何驱动器号上的Windows或Linux上获得正确的路径,您可以执行以下操作:
path = path.replaceFirst("^/(.:/)", "$1");
Run Code Online (Sandbox Code Playgroud)
这样说:如果字符串的开头是斜杠,那么一个字符,然后一个冒号和另一个斜杠,用字符,冒号和斜线替换它(保留前导斜杠).
如果您使用的是Linux,则不应该在路径中使用冒号,并且不会匹配.如果你在Windows上,这适用于任何驱动器号.