开发者

Browse For a Text File to Read From

I'm trying to make a program in Java where the user is able to click a browse button and then be able to browse through directories for a text file.

Once they select that text file, I plan to read from it in order to load some of its data into variables, but the part im working on right now is just getting the browse button to work; then I will move onto the reading from the text file.

Right now I have a JButton with an empty action listener, and a non-editable text field in which i want to load the files path into.

I see others ta开发者_运维百科lking about the JFileChooser class, but the examples they are always using the JFileChooser to for saving files or actually opening them, I do not want the file to be opened for the user, I just want the path so I know where to read from. Let me know if you need more information.

Thank you for all the help, I was able to find the information I needed with in the JavaDocs, I now have my absolute path loaded into the JTextField and from here I will move onto the reading of the file, Thanks all.

browseButton.addActionListener( new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        // yet to come...
    }
});


JFileChooser does not actually open the file. What it returns is the path to the file(s) chosen. JFileChooser is definitely the way to go, based on your description of the issue. It allows the user to browse to a file, whose path is then returned back to you, and from there you can do whatever you need with the file.

So, the actionPerformed(ActionEvent e) method on the browseButton object is where you would trigger the appearance of the JFileChooser. You also attach an ActionListener to the JFileChooser, to react to the event that closes the dialog. In the actionPerformed method, attached to the ActionListener that is listening to the JFileChooser is where you will be able to get at the value selected by the user (i.e. if it was a file chosen, a folder, or if they canceled the dialog without selecting anything).


The official tutorial by Sun provides examples (and example code) for both saving and opening.

Also, the JFileChooser does not read or open the file! It only provides a user-frontend to search for the file to open/save and then returns a File-object which you can then use to read from the file (with a BufferedReader (for plain text) for example).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜