Question

I'm writing a translator program that reads the translations from a text file. This method reads from the text file and adds it to a Map object that i'm using for the dictionary.

public Map<String, String> loadTranslations() throws IOException {
    Map<String, String> translations = new HashMap<String, String>();
    BufferedReader in = null;
    try {
        in = new BufferedReader(new FileReader(System.getProperty("user.dir") + "\\resource\\translations.txt"));
        englWord = in.readLine();
        frenWord = in.readLine();
        translations.put(englWord, frenWord);
        System.out.println(englWord + "\n" + frenWord + "\n" + translations);
    } catch(Exception e) {
        JOptionPane.showMessageDialog(this, "An Error Occured!", "Error!", JOptionPane.ERROR_MESSAGE);
        e.printStackTrace();
    } finally {
        in.close();
    }
    JOptionPane.showMessageDialog(this, "Updated!", "", JOptionPane.INFORMATION_MESSAGE);
    return translations;
}

But whenever I run it, instead of printing the words from the text file it prints this;

潮攍ੵ渍ੴ睯ഊ摥畸ഊ瑨牥攍ੴ牯楳ഊ景畲ഊ煵慴牥ഊ晩癥ഊ捩湱ഊ獩砍ੳ楸ഊ獥癥渍ੳ数琍੥楧桴ഊ桵楴ഊ湩湥ഊ湥畦ഊ瑥渍੤楸
null
{潮攍ੵ渍ੴ睯ഊ摥畸ഊ瑨牥攍ੴ牯楳ഊ景畲ഊ煵慴牥ഊ晩癥ഊ捩湱ഊ獩砍ੳ楸ഊ獥癥渍ੳ数琍੥楧桴ഊ桵楴ഊ湩湥ഊ湥畦ഊ瑥渍੤楸=null}

The text file just lists the first ten letters in english and french so the output should be something like;

one
un
{one=un}

How do I fix this?

Was it helpful?

Solution

If you don't specify an encoding you get a default value that depends on how the JVM gets initialized. You can specify an explicit encoding like this:

    FileInputStream fis = new FileInputStream("test.txt");
    InputStreamReader isr = new InputStreamReader(fis, "UTF8");
    BufferedReader in = new BufferedReader(isr);

This code reads a file where it is assuming the content is encoded in UTF8.

See the Oracle tutorial on Character and Byte Streams.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top