razshan
razshan

Reputation: 1138

How to import data from textfiles to JTextArea?

I have a text file that has 10 lines of information. How to copy paste that info in a JTextArea?

public void createPage4()
    {
    panel4 = new JPanel();
    panel4.setLayout( new BorderLayout() );

    BufferedReader log=null;

        try {


        FileReader logg =new FileReader("logsheet.txt");
            log = new BufferedReader(logg); 

        textArea = new JTextArea("how do I get all the content of logsheet, I can get it on the command window as shown below");




        for (int x = 0 ; x<10; x++){

            System.out.println(log.readLine());

             }


             panel4.add(textArea);

Upvotes: 1

Views: 2402

Answers (3)

camickr
camickr

Reputation: 324108

textArea.read(new BufferedReader(new FileReader("logsheet.txt"), null));

Upvotes: 1

Amokrane Chentir
Amokrane Chentir

Reputation: 30385

You need to use Append() to copy each line you read to the end of your JTextArea component.

append

public void append(String str) Appends the given text to the end of the document. Does nothing if the model is null or the string is null or empty. This method is thread safe, although most Swing methods are not. Please see How to Use Threads for more information.

Parameters: str - the text to insert See Also: insert(java.lang.String, int)

Your for loop will become:

for (int x = 0 ; x<10; x++){
    textArea.append(log.readLine() + "\n");
}

Upvotes: 1

Michael Berry
Michael Berry

Reputation: 72284

Something like the following should do the trick:

BufferedReader reader = new BufferedReader(new FileReader("logsheet.txt"));
String line;
while((line = reader.readLine()) != null) {
    textArea.append(line).append("\n");
}
reader.close();

Here you're reading the entire contents of the file (so it doesn't matter how many lines it has), appending the contents to a string builder and then setting the text area to the contents of the string builder. (It's also important to remember to close your reader after you've finished with it.)

The above will just append to the text area. If you want to clear it first, add textArea.setText(""); before the while loop.

If you want to make sure only the first 10 lines are read, add a counter, increment it on each iteration of the while loop and then exit if it's 10 or above (I'll leave that as an implementation exercise if you need it!)

Upvotes: 0

Related Questions