java - 按下按钮后读取文件

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

最佳答案

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

看到这个了吗?

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

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

关于java - 按下按钮后读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16653051/

相关文章:

java - 优化从大表中获取数据

java - 如何在jrxml中迭代HashMap(Arraylist)?

java - 更改 TableCellEditor 对象的对齐方式

java - 关于制作基本游戏的对象声明和一些图像导入语句的问题

java - 性能下降从 Hazelcast 2.5 升级到 3+

java - 如何切换maven项目?

java - PreparedStatement抛出索引未超出范围时抛出超出范围

java - Swing gui 未正确隐藏/显示

java - 如何仅获取特定文件的父目录名称

java - 使用 Java 创建重新链接