0

我试图创建一个程序,让您选择一个文件,读取它然后将结果打印出来......这就是我到目前为止所拥有的

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”,我实际上对这些事情知之甚少..

4

2 回答 2

1

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

看到这个了吗?

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

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

于 2013-05-20T15:41:31.937 回答
0

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

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

because if file is in same directory where you project is then work but when selected file reside in different places then need to use absolutepath of selected file.

于 2013-05-21T07:11:20.573 回答