简体   繁体   中英

Working with UTF-8 characters, Java

My basic code is trying to check files exitence, based on paths, but it can't deal with Unicode Characters:

        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        File f = new File(input);
        if (f.exists()) {
            System.out.println("File is Found, According to java.io");
        } else {
            System.out.println(f.toString() + " is Not Existed, According to java.io ");
        }

        Path x = Paths.get(input);
        if (Files.exists(x)) {
            System.out.println("File is Found, According to java.nio");
        } else {
            System.out.println(x.toString() + " is Not Existed, According to java.nio");
        }

when the input (ie. file path) is in ASCII, the code works fine, but when the input contains UTF-8 chars, the code fails in both :

1- printing the input properly.

2- determining does the file exist (ie. even when the file exists, the code tells that file is not exited)

Example:

input:

c://€.jpg

output:

c:\\ .jpg is Not Existed, According to java.io

c:\\ .jpg is Not Existed, According to java.nio

I use NetBeans, Java 1.8, maven.

PS : I tried to use:

run with :

-Dfile.encoding=UTF-8

add the followign to project properties :

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

, but nothing happened.

Any help, please?

Precisely, you don't need a file encoding, but an input encoding. Therefore you can specify a charset for your Scanner using the Scanner(InputStream source, String charsetName) constructor:

Scanner scanner = new Scanner(System.in, "UTF-8");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM