How to import a Text file content to a JTextArea in a Java application?

后端 未结 5 2055
夕颜
夕颜 2020-12-18 16:19

how to import a Text file content to a JTextArea in a Java application using JFileChooser?

5条回答
  •  青春惊慌失措
    2020-12-18 17:09

    To import the contents of a file into a JTextArea you simply follow these steps!

    1. Create a frame and add a JTextArea to it.
    2. You declare and initialize a JFileChooser.
    3. You add a listener to the JFileChooser.
    4. In your actionPerformed, you should take the file that was selected and pass it to a method that would read this file(see NB below).
    5. In that method, you open a file reader and read the contents of the file, line by line. As you do so, you append each line to the JTextArea.
    6. When you get to the end of the file, you close the file reader.
    7. Run the program and you should be good to go.

    The above steps are good enough to perform your task. However, when you give it a try, i would edit my post and add a possible solution.

    NB: You must note that when you select a file with a JFileChooser, it returns an Object of type File. You should then use the getName() method provided by the File class to get the name of the file.

    Links that might be of help!
    JFileChooser
    File
    Java tutorials on how to use the JFileChooser

提交回复
热议问题