一般操作
public static void main(String[] args) throws Exception {
try{
String path = Test.class.getClassLoader().getResource("").getPath();
String realPath = path = path+"key/public.key";
System.out.println(realPath);
byte[] publicKeyBytes = Files.readAllBytes(Paths.get(realPath));
}catch (Exception e){
e.printStackTrace();
}
}
一般操作导致的结果
realPath:/E:/idea/algorithm/target/classes/key/public.key
java.nio.file.InvalidPathException: Illegal char <:> at index 2: /E:/idea/algorithm/target/classes/key/public.key
at sun.nio.fs.WindowsPathParser.normalize(WindowsPathParser.java:182)
at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:153)
at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:77)
at sun.nio.fs.WindowsPath.parse(WindowsPath.java:94)
at sun.nio.fs.WindowsFileSystem.getPath(WindowsFileSystem.java:255)
at java.nio.file.Paths.get(Paths.java:84)
at com.hufei.algorithm.Test.main(Test.java:34)
一般操作说明
从相关日志我们可以看出,在windows操作系统输出的path会在路径前面多了一个/.从而导致使用Paths.get无法处理,最终抛出异常。
正常的操作
public static void main(String[] args) throws Exception {
try{
String path = Test.class.getClassLoader().getResource("").toURI().toString();
path = path+"key/public.key";
URI uri = new URL(path).toURI();
byte[] publicKeyBytes = Files.readAllBytes(Paths.get(uri));
}catch (Exception e){
e.printStackTrace();
}
}
正常操作说明
我们通过使用path.get对应的重载函数,将URI作为入参,可以很好地解决windows 下面的问题