Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java java.io.filenotfoundexception for file path with cyrillic characters

I have a file whose name contains characters not only from the plain ASCII character set, but also from a non-ASCII character set. In my case it contains Cyrillic characters.

Here's a snippet of my code:

String fileName = "/Users/dnelepov/Downloads/тест изображение.png";
File sendFile = new File(fileName);
if (sendFile.exists()) {
    // Some code
}

The code in sendFile.exists if block is not being executed.

Why isn't the file recognized?

My system configuration locale

LANG="ru_RU.UTF-8"
LC_COLLATE="ru_RU.UTF-8"
LC_CTYPE="ru_RU.UTF-8"
LC_MESSAGES="ru_RU.UTF-8"
LC_MONETARY="ru_RU.UTF-8"
LC_NUMERIC="ru_RU.UTF-8"
LC_TIME="ru_RU.UTF-8"
LC_ALL="ru_RU.UTF-8"

uname -a

Darwin Dmitrys-MacBook-Pro.local 11.4.2 Darwin Kernel Version 11.4.2: Thu Aug 23 16:25:48 PDT 2012; root:xnu-1699.32.7~1/RELEASE_X86_64 x86_64

java -version

java version "1.7.0_21"
Java(TM) SE Runtime Environment (build 1.7.0_21-b12)
Java HotSpot(TM) 64-Bit Server VM (build 23.21-b01, mixed mode)

UPDATE

I found that this error is on JDK from Oracle.

I created project on Eclipse, and file was found. I checked project properties and found Mac OS 6 JDK.

Then I change it to JDK 7 and file was not Found again.

My problem is that I need to use JDK 7 with JavaFX. Not Mac OS version. So my problem still exists.

I've made a video to show this error Video with error

UPDATE 2

Thanks to eumust for answer, this code works:

Path path = Paths.get("/Users/dnelepov/Downloads/test/");
    Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path oneF, BasicFileAttributes attrs) throws IOException {
            System.out.println("FILE:" + oneF);
            if (Files.exists(oneF)) {
                System.out.println("EXISTS:" + oneF);
            }
            return FileVisitResult.CONTINUE;
        }
    });

https://stackoverflow.com/a/17481204/849961

like image 521
Dmitry Nelepov Avatar asked Jun 06 '13 17:06

Dmitry Nelepov


Video Answer


1 Answers

Just for kicks, this hack might work:

String fDir = "/Users/dnelepov/Downloads/";
char[] fileName = "тест изображение.png".toCharArray();
File root = new File(fDir);
File[] folder = root.listFiles();

for (File f : folder) 
    if (Array.equals(fileName, f.getName().toCharArray()) {
        //code here
          ...
    }

I don't know if it will yield any different results for you, especially since it may be just a weird encoding issue with the file name, but this could help shed some light on the situation. If the code doesn't execute, do a print on the int (ascii vals) of the charArray for all of the file names in the directory -- find the one you're looking for and see how the chars are encoded and why it's not equal.

like image 74
Eric Wich Avatar answered Sep 27 '22 18:09

Eric Wich