How to read a text file into jtextarea in Java Swing

橙三吉。 提交于 2019-11-29 15:27:14

You don't need the while loop, or the readLine method. Just call jtextArea1.read(reader, "jTextArea1")

Edit: update following your comment. If you want to skip all lines starting with >, you will need to read the file manually and then append each line to your textArea.

So something like:

String line;
while ((line = reader.readLine()) != null)
{
    if (!line.startsWith(">"))
    {
        jTextArea.append(line + "\n");
    }
}
Bhushankumar Lilapara

Use:

FileReader reader = new FileReader("filename.txt");
txtarea.read(reader, "filename.txt"); //Object of JTextArea

You need only the above two lines to read from a file and put it into JTextArea...

Alexey Ivanov

The problem must have been solved by the time, yet there's still no answer to the question why the first two lines are skipped.

You create reader and then read the first two lines from the file, remaining lines are loaded into jTextArea1.

Your code:

/* 1 */ while((textLine=reader.readLine())!=null){
/* 2 */     textLine = reader.readLine();
/* 3 */     jTextArea1.read(reader,"jTextArea1");
        } 

Line 1 reads the first line from the file. Then in the body of while you read the second line from the file at line 2. Line 3 reads the rest of the file into jTextArea1.

On the next iteration of the while loop, reader.readLine() returns null since the file is completely read.


To load text in a JTextComponent use its read method as suggested by Phill and Bhushankumar.

The second parameter to read is not used by JTextArea, so it's safe to pass null. This second parameter is usually used to store to URL of the loaded file to resolve relative references, for example links in an HTMLDocument.

Talha Ahmed Khan

textLine = reader.readLine(); is called twice...

Fixed:

try {
    String textLine;
    FileReader fr = new FileReader("ad.txt");
    BufferedReader reader = new BufferedReader(fr);

    while((textLine=reader.readLine()) != null){
        // textLine = reader.readLine(); // Remove this line
        jTextArea1.read(reader, "jTextArea1");
    }
}
catch (IOException ioe) {
    System.err.println(ioe);
    System.exit(1);
}
giacomo

Correctly is:

try {
    FileReader fr = new FileReader("tablica.txt");
    BufferedReader reader = new BufferedReader(fr);

    do {
        l.read(reader, null);
    }

    while ((textLine=reader.readLine()) != null)
        ;

}

catch (IOException ioe) {
    System.err.println(ioe);
    System.exit(1);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!