11

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 14 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
Cœur
  • 37,241
  • 25
  • 195
  • 267
Dennis C
  • 24,511
  • 12
  • 71
  • 99

2 Answers2

9

Could it be related to File.exists() fails with unicode characters in name

n00begon
  • 3,503
  • 3
  • 29
  • 42
mark-cs
  • 4,677
  • 24
  • 32
  • 1
    +1 - the cure would be to change the OS locale settings so that it used an file encoding that was compatible with the characters in the filename. – Stephen C Apr 14 '11 at 13:50
  • Again another example that Sun Micro-system do never fix bug for years. Is it really so hard to accept and to agree a bug? – Dennis C Apr 15 '11 at 01:35
  • I am thinking what value of LC_ALL I should use. As that bug report page will never provide any useful information. May be all of us should learn from Adrian http://www.techgoss.com/Story/3226S14-Dedication-to-open-source.aspx – Dennis C Apr 15 '11 at 01:43
  • Anyone call tell if NIO2 in Java7 fix the bug or the bug still there? – Dennis C Sep 03 '11 at 06:22
  • While Dennis' exact use-case is not the same as mine, java.nio.file fixed the related problems I was having. http://stackoverflow.com/questions/3072376/how-can-i-open-files-containing-accents-in-java – Sridhar Sarnobat Feb 27 '14 at 04:21
0

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.

Andrew White
  • 52,720
  • 19
  • 113
  • 137