I am using Java in Eclipse trying to write a program that lets me choose a file and then reads what's in it. So far, all I can get it to do is print out the name of the file itself, not the text inside it. Ideally, I would like to it find certain strings and only display those, but I figure I need to figure out how to get it to read anything at all before I get to that step. Here's what I have.
import java.awt.FlowLayout;
import java.awt.event.*;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
public class MainFrame extends JFrame implements ActionListener{
JButton button;
MainFrame(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
button = new JButton("Select File");
button.addActionListener(this);
this.add(button);
this.pack();
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==button) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File("/Users/ccampbell/Desktop")); //sets current directory
int response = fileChooser.showOpenDialog(null); //select file to open
//int response = fileChooser.showSaveDialog(null); //select file to save
if(response == JFileChooser.APPROVE_OPTION) {
File file = new File(fileChooser.getSelectedFile().getAbsolutePath());
System.out.println(file);