@HectorLector's response will optimize the reading a bit, but they're right; utltimately, reading a file is going to take as long as it takes. I suspect that your underlying question might be "how can I make my UI responsive while I'm reading this file?" - right now, since you're doing the reading inside an ActionListener
, your UI will be completely blocked while the file is read, which makes for a terrible user experience.
The answer to this is that long-running operations like filesystem access should be done on a background thread. Consider using a SwingWorker
(see the tutorial) for a task like this; the worker thread can build the string and use the done()
method to update the text area (or, if you want to show the file as it's being read, use a combination of the publish()
and process()
methods).
Also, as a side note, be sure you're close()
ing that BufferedReader
you're using to read the file. Wrap the reading itself in a try
block, and close inside finally
in case there are any problems during reading. Something like this:
BufferedReader in = new BufferedReader(new FileReader(f));
StringBuilder output = new StringBuilder();
try {
while (in.hasNext()) {
output.append(in.readLine());
output.append("\n");
}
finally {
in.close();
}