简体   繁体   中英

Java doesn't display accent words correctly

I have a java program that saves a text file and then outputs it contents in a dialog. When I run the program inside my IDE (BlueJ) the display is as follows: BlueJ内部的程序在此输入图像描述

As you can see in the dialog the line "1º) Mónica" appears correctly.
But when I run the same program outside the IDE the "Mónica" doesn't appear right, as you can see in the picture:
BlueJ以外的计划

How can I fix this to always display the right output?

this is the code that reads the text file to a string

public String recordesString()
    {
        Premios premios = new Premios();
        File recordes = new File("recordes.txt");
        if(!recordes.exists()) {
            if(!client.isConnected())
                openFTPSession();
            downloadRecordes(); // this downloads the recordes.txt file
        }
        Scanner s = null;
        try {
            s = new Scanner(recordes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String string = "";
        String linha = null;
        for(int i = 1; s.hasNext(); i++) {
            linha = s.nextLine();
            String palavra[] = linha.split(" ",2);
            string += i+"º) "+palavra[1] +"  "+ premios.getPremio(Integer.parseInt(palavra[0]))+"\n";
        }
        s.close();
        try {
            Files.deleteIfExists(Paths.get(ficRecordes));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return string;
    }

Scanner reads the file using the underlying platform's default charset.

See http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner(java.io.File)

I'd expect the file is encoded in UTF-8 and when you run outside the IDE, the default charset is ISO-latin-1 or so. If you specify the file's encoding when creating the scanner, the results will be predictable.

s = new Scanner(recordes, "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