天天看點

Exception in thread "main" java.nio.file.InvalidPathException: Illegal char at index 13: d:\logs

Exception in thread "main" java.nio.file.InvalidPathException: Illegal char < > at index 13: d:\logs\b.txt                                   

    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 SocketServer.main(SocketServer.java:29)

*****

開始網上百度,說jdk版本問題,我把自己用了許久的1.8_162,換成了1.8_211,但是**仍然報錯

(雖然jdk1.12都已經橫空出世,但是我還在用1.8,跟不上,真的更新太快了。。。)

也有人說是特殊字元,但說的不太詳細,是以自己解釋一下

*****

WindowsPathParser.java:182  //代碼報錯處,代碼中,抛出異常的原因,點選進入,就可以看到

if (isInvalidPathChar(var6)) {  //這個判定說明你的path的路徑中有以下非法字元,再次進入方法看到

     throw new InvalidPathException(var1, "Illegal char <" + var6 + ">", var2);

}

private static final boolean isInvalidPathChar(char var0) {

     return var0 < ' ' || "<>:\"|?*".indexOf(var0) != -1;  //這裡是具體的非法字元

//非法字元(空格鍵對應ascii表的32),這說明你path路徑中,有ascii表32位以前的字元(一般為不可見字元,或者是\r \t等等 )

或者有"<>:\"|?*"這裡面的幾個符号

}

ASCII表參考查詢網址百度百科

https://baike.baidu.com/pic/ASCII/309296/0/c2fdfc039245d688c56332adacc27d1ed21b2451?fr=lemma&ct=single#aid=0&pic=c2fdfc039245d688c56332adacc27d1ed21b2451

//**下面舉兩個例子,都會報同樣的錯誤

        //例子1.含有特殊字元*号情況

        Path path1 = Paths.get("d:\\logs\\a*.txt");

        //==================================================================================

        //例子2.含有不可見字元情況

        FileInputStream fileOutputStream = new FileInputStream("d:\\logs\\a.txt");

        //d:\logs\a.txt檔案中的内容就是d:\logs\a.txt

        //這裡建立了一個30長度的位元組數組

        byte[] bytes = new byte[30];

        //将他d:\logs\a.txt寫入這個位元組數組,因為d:\logs\a.txt内容長度不夠30,是以bytes中的後面會出現NUL這樣的不可見字元

        fileOutputStream.read(bytes);

        String fileName = new String(bytes);

        //但是轉成字元串輸出他就是這樣的d:\logs\a.txt,看不出任何的毛病

        System.out.println(fileName);//看到的結果就是d:\logs\a.txt

        //但是你在這一步操作時,就會報錯

        //java.nio.file.InvalidPathException: Illegal char < > at index 13: d:\logs\a.txt

        //因為fileName中含有不可見字元

        Path path2 = Paths.get(fileName);

//*******************報以上錯誤的還有很多情況,在這裡不做具體分析了

歡迎大家點贊,關注,轉發......,快點扶我上位。