Java readLine()无法正常工作 [英] Java readLine() not working properly

查看:286
本文介绍了Java readLine()无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个翻译程序,该程序从文本文件中读取翻译内容.此方法从文本文件中读取并将其添加到我用于词典的Map对象中.

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}

我该如何解决?

推荐答案

如果不指定编码,则会得到默认值取决于如何初始化JVM .您可以指定像这样的显式编码:

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);

此代码读取一个文件,假设该文件的内容以UTF8编码.

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

请参见有关字符和字节流的Oracle教程

这篇关于Java readLine()无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆