Reputation: 197
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
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
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
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:
DataInputStream
for no obvious reasonBufferedReader
in
which is in the middle of the chain of inputs for some reason... I'd expect to close either br
or fstream
in
if there's no exception (use a finally
block or a try-with-resources statement if you're using Java 7)Body
, violating Java naming conventionsException
rather than IOException
- prefer to catch specific exceptionsUpvotes: 5