简体   繁体   English

读取文本并将文件文本输入到JTextArea

[英]Read text and input file text to JTextArea

What's wrong with my code? 我的代码有什么问题? I'm trying to read text file and then put the text to JTextArea , but its input only consists of the last line of text. 我正在尝试读取文本文件,然后将文本放入JTextArea ,但其输入仅包含文本的最后一行。 What's wrong? 怎么了?

Code : 代码

public void read() {
    int returnVal = fc.showOpenDialog(null);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        pavadinimas = file.getName();
        try {
            FileInputStream fstream = new FileInputStream(fc.getCurrentDirectory() + "/" + pavadinimas);
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            while ((strLine = br.readLine()) != null) {
                tekstas.setText(strLine);
            }
            in.close();
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

使用append函数代替settext

Don't reinvent the wheel. 不要重新发明轮子。 There is no need to write looping code or append you own end-of-line string. 无需编写循环代码或附加您自己的行尾字符串。

Use the JTextArea.read(...) method. 使用JTextArea.read(...)方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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