reza ostadi
reza ostadi

Reputation: 197

How do i read multiple lines from a file into a string to put in jTextArea?

ive tried many different things and this is the only thing that has worked with reading one line from a file so far...

try{

        FileInputStream fstream = new FileInputStream("./Saves/Body.sav");
        BufferedReader br = new BufferedReader(new InputStreamReader(infstream);
        String strLine;    
        while ((strLine = br.readLine()) != null)   {      
        System.out.println(strLine);
        w1.Body = strLine;
        }  
        in.close();
          }catch (Exception e){//Catch exception if any
        System.err.println("Error: " + e.getMessage());
        }

I am trying to create a load function so i can load text from a file onto a string onto a jTextArea... Without any sort of openfiledialog

Upvotes: 0

Views: 2674

Answers (3)

Andrew Thompson
Andrew Thompson

Reputation: 168825

How do i read ... put in jTextArea?

Ignoring the entire middle of that statement, I suggest.

File file = new File("./Saves/Body.sav");
FileReader fileReader = new FileReader(file);
textArea.read(fileReader, file);

Upvotes: 3

Dan D.
Dan D.

Reputation: 32391

You can use a StringBuilder (or the synchronized version StringBuffer) and keep appending strLine to it. Declare it this way:

StringBuilder s = new StringBuilder();

and in the while loop:

s.append(strLine + "\n");

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500155

I'd personally use Guava:

File file = new File("Saves", "Body.sav");
String text = Files.toString(file, Charsets.UTF_8);

That's assuming it's a UTF-8 file, of course. Adjust accordingly.

Your current code has a number of issues:

  • It creates a DataInputStream for no obvious reason
  • You probably don't gain much from using BufferedReader
  • You're not specifying the character encoding, so you're getting the platform default, implicitly, which is almost never a good idea.
  • You're closing in which is in the middle of the chain of inputs for some reason... I'd expect to close either br or fstream
  • You're only closing in if there's no exception (use a finally block or a try-with-resources statement if you're using Java 7)
  • You appear to have a field called Body, violating Java naming conventions
  • You're catching Exception rather than IOException - prefer to catch specific exceptions
  • You're "handling" the exception by effectively ignoring it, which is almost never appropriate. (The code which reads a file is very rarely the right code to decide what to do with an exception.)

Upvotes: 5

Related Questions