按下按钮后读取文件

时间:2013-05-20 15:36:17

标签: java swing java-io jfilechooser

我试图创建一个程序,让你选择一个文件,读取它然后打印结果......这是我到目前为止

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Bebras braces matcher");
        JButton selectf = new JButton("Open file");
        selectf.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String cmd = e.getActionCommand();
                if(cmd.equals("Open file")) {
                    JFileChooser chooser =new JFileChooser();
                    FileFilter filefilter = new FileNameExtensionFilter("","txt");
                    chooser.setFileFilter(filefilter);
                    int returnVal = chooser.showOpenDialog(chooser);
                    if(returnVal==JFileChooser.APPROVE_OPTION) {
                        FileName=chooser.getSelectedFile().getName();
                        System.out.println(FileName);       
                    }
                }
            }
        });
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500,500);
        frame.add(selectf);
        frame.setVisible(true);

    }
    public static void countChar() throws FileNotFoundException {
        Scanner scan = null;
        try {
            scan = new Scanner(new File(FileName));
        }
        catch (FileNotFoundException e) {
        }
        while (scan.hasNext()) {
            String character = scan.next();
            int index =0;
            char close = '}';
            char open = '{';
            while(index<character.length()) {

                if(character.charAt(index)==close){
                    CloseCount++;
                }
                else if(character.charAt(index)==open) {
                    OpenCount++;
                }
                index++;
            }
        }
        System.out.println("Opened: "+OpenCount+"Closed: "+CloseCount);
    }
    private static String FileName;
    private static int CloseCount = 0;
    private static int OpenCount = 0;
    private static final long serialVersionUID = 7526472295622776147L;
}

它运行正常,只是没有做它需要的......我怎么让“countChar”运行?因为它不打印我应该...

我忘了提及,如果我在打印出文件名后调用它,我会得到这个错误:“未处理的异常类型FileNotFoundException”,我实际上对这些东西的了解真的很少..

2 个答案:

答案 0 :(得分:1)

你快到了!您只是打印出文件名而不是调用该方法。

看到了吗?

if(returnVal==JFileChooser.APPROVE_OPTION) {
    FileName=chooser.getSelectedFile().getName();
    System.out.println(FileName);       
}

而不是{或之前或之后,如果您愿意)System.out.println(FileName);,只需添加countChar();

答案 1 :(得分:0)

您只需在FileName中指定文件名而不是文件路径。 所以你用这个

if(returnVal==JFileChooser.APPROVE_OPTION) {
FileName=chooser.getSelectedFile().getAbsolutePath();
countChar();

因为如果文件位于您项目所在的同一目录中,那么当所选文件位于不同的位置时,则需要使用所选文件的绝对路径。

相关问题