How to fix java when if refused to open a file with special character in filename?
How to open a file, with a special character which Java refused to open?
At the beginning I guess it was a charset encoding problem as I read the filename wrong from a log file. But later I found that, it is possible a bug of JVM and I need a workaround.
Real example better then words
import java.io.*;
public class WTF{
public static void main(String[] s)throws Exception{
File f2=new File(".");
for (File subFile : f2.listFiles()) {
System.out.println(subFile.getName());
System.out.println(subFile.exists());
System.out.println(new FileInputStream(subFile));
}
}
}
With a result
[USER@SERVER ZZZ]$ java -cp . WTF
WTF.class
true
java.io.FileInputStream@732dacd1
WTF.java
true
java.io.FileInputStream@3bad086a
ABC_�%81DEF.txt
false
Exception in thread "main" java.io.FileNotFoundException: ABC_�%81DEF.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at java.io.FileInputStream.<init>(FileInputStream.java:66)
at WTF.main(WTF.java:8)
And the folder contains
[USER@SERVER ZZZ]$ ls -lb
-rw-r--r-- 1 USER GROUP 8 Apr 1开发者_如何学JAVA4 20:54 ABC_\303%81DEF.txt
-rw-r--r-- 1 USER GROUP 1068 Apr 14 20:58 WTF.class
-rw-r--r-- 1 USER GROUP 554 Apr 14 20:58 WTF.java
Could it be related to File.exists() fails with unicode characters in name
A possible workaround would be to use a system command to either rename or link to the file using only standard "friendly" chars. Seems hacky but I would think it would work.
精彩评论