java - How to read from a file into a JTextArea (GUI) line by line? -


i reading in file (which list of names , contact numbers) , displaying in textarea in gui. file reads in fine , text displayed. want each line file on new line on gui. each name , address on new line. how do this? code far, doesn't display each line file on new line on gui.

public void books() throws ioexception {         string result = " ";         string line;         linenumberreader lnr = new linenumberreader(new filereader(newfile("books2.txt")));         while ((line = lnr.readline()) != null) {             result += line;`         }           area1 = new jtextarea(" label 1 ");         area1.settext(result);         area1.setbounds(50, 50, 900, 300);         area1.setforeground(color.black);         panelmain.add(area1);      } 

you don't need read line line. do:

string result = new string(files.readallbytes(paths.get("books2.txt")),                            standardcharsets.utf_8); 

this, of course, require more memory: first read bytes, , create string. if memory concern, reading whole file @ once bad idea anyway, not mention displaying in jtextarea!

it may not handle different line endings properly. when use readline(), strips line of endings, cr lf, lf or cr. way above read string as-is. maybe reading line-by-line not bad idea after all. i've checked—jtextarea seems handle cr lf right. may cause other problems, though.

with line-by-line approach, i'd like

string result = string.join("\n",         files.readalllines(paths.get("books2.txt"),             standardcharsets.utf_8)); 

this still strips last line of eol. if that's important (e. g., want able put text cursor on line after last one), 1 more + "\n".

all of above requires java 7/8.

if you're using java 6 or something, way ok, except that:

  1. replace linenumberreader bufferedreader—you don't need line numbers, you?
  2. replace string result stringbuilder result = new stringbuilder(), , += result.append(line).append('\n').
  3. in end, use result.tostring() string.

Comments