From your question I assume you have gotten this far:
BufferedReader in = null;
try{
in = new BufferedReader(new FileReader("C:\\path\\to\\file\\info.txt"));
String str = in.readLine();
ArrayList<String> textList = new ArrayList<String>();
while((str = in.readLine()) != null){
textList.add(str); //saves each line that is read from the file
}
//-->This is where you will add later code
}catch(IOException e){
System.out.println("Error reading file");
e.printStackTrace();
}
From here you should use the
JTextArea.append()
method like so:
--Insert after the while loop in the readFile() method.
for(String s:textList){
yourJTextArea.append(s +"\n");
}
A full example:
import java.awt.Dimension;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class TextRead extends JFrame{
static JTextArea mytextArea;
public TextRead(){
super("TextRead");
mytextArea = new JTextArea();
mytextArea.setPreferredSize(new Dimension(500,500));
getContentPane().add(mytextArea);
setContentPane(getContentPane());
pack();
setVisible(true);
setSize(500,500);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
readFile();
}
private void readFile() {
BufferedReader in = null;
try{
String path = "C:\\Users\\steve_000\\Desktop\\info.txt"; //<--your path goes here!
in = new BufferedReader(new FileReader(path));
String str = in.readLine();
ArrayList<String> textList = new ArrayList<String>();
while((str = in.readLine()) != null){
textList.add(str); //saves each line that is read from the file
}
for(String s: textList){
mytextArea.append(s + "\n"); //prints each line consecutively
}
}catch(IOException e){
System.out.println("Error reading file");
e.printStackTrace();
}
}
public static void main(String... args){
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run(){
runGUI();
}
});
}
public static void runGUI() {
TextRead tr = new TextRead();
JFrame.setDefaultLookAndFeelDecorated(false);
}
}