windows 环境下Paths.get导致的问题

一般操作

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 下面的问题

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值