Friday, July 31, 2009

In java, How can I display the contents of a text file in a textarea using the open dialog box?

Using swing components I created a text area and a butten named 'open'. When I click the 'open' button an opendialog box should appear and thus I can select a text file. How can I display the contents of the file into the text area? Can it be done only with the concept of files only? If you know please wite the source code.

In java, How can I display the contents of a text file in a textarea using the open dialog box?
Using the opendialog box will return the name and path of the file, then use it accordingly. PS I've not checked this code works so there may be the odd typo in here.





String allText = "";





String filePath = "c:/folder/file.txt";





BufferedReader r = new BufferedReader( new FileReader( filePath ) );





String line = r.readLine();





while ( line!=null ) {


allText += line;


line = r.readLine();


}





r.close();





yourTextArea.setText( allText );








This should get you along the right tracks
Reply:Look up JFileChooser and limit the selection to files instead of directories. You will find more information if you google about Jfilechooser. You can used buffered reader or something similar to read the text and use the set Text in text area to the text read by the reader.


No comments:

Post a Comment