Use the read(...)
method of the JTextArea
. It will do the reading of the text from the file for you.
Reading from a file into JTextArea
Question
Im trying to read from a text file into a JTextArea in a GUI. But the text is not appearing. I have a scroll area within my text area but I get an error if I try to read the file to this so im reading it to the TextArea, but im not sure if this is correct.
String readFrom = "C:\\Users\\john\\directory.txt";
int num;
String line;
Scanner inFile = new Scanner(new FileReader(readFrom));
BufferedReader in = new BufferedReader(new FileReader(readFrom));
num = inFile.nextInt();
JTextArea table = new JTextArea(55, 15); //text area for directory
JScrollPane table1 = new JScrollPane(table);
table.setEditable(false);
panel.add(table1);
for( int i=0; i< num; i++){
line = in.readLine();
table.read(in, "table1");
}
Solution
OTHER TIPS
Use this to read the file and return a String with your text:
String readFile(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
then add the string to your text area by append() method:
table.append(readFile(fileName));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow