Tadas
Tadas

Reputation: 89

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. 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());
        }
    }
}

Upvotes: 0

Views: 75

Answers (2)

camickr
camickr

Reputation: 324108

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.

Upvotes: 0

Prasanth Louis
Prasanth Louis

Reputation: 5056

Use the append function instead of settext

Upvotes: 1

Related Questions