FileNotFoundException JFleChooser和FileReader JAVA

时间:2016-02-28 11:06:15

标签: java swing java-io filenotfoundexception

我一直在编写一个代码,它从JFileChooser获取文件的绝对路径,并使用它通过BufferedReader读取它。

这是代码:

    package TestPackage;

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import javax.swing.JFileChooser;
    import javax.swing.filechooser.FileNameExtensionFilter;
    import java.text.ParseException;
    import java.util.concurrent.ExecutionException;
    import javax.swing.JOptionPane;

    /**
     *
     * @author MRx
     */
    public class MainFrame extends javax.swing.JFrame {

    /** Creates new form MainFrame */
    public MainFrame() {
        initComponents();
        this.setLocationRelativeTo(null);
    }

File f;
String filename;
JFileChooser chooser;

private void openModelActionPerformed(java.awt.event.ActionEvent evt) {                                          
// TODO add your handling code here:
    chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("TEXT FILES", "txt", "text");
    chooser.setFileFilter(filter);
    chooser.showOpenDialog(null);
    f = chooser.getSelectedFile();
    filename = f.getAbsolutePath();

}                                         

private void btnRunActionPerformed(java.awt.event.ActionEvent evt) {                                       
// TODO add your handling code here:
    JOptionPane.showMessageDialog(null, filename);
{

public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }

    public String readSpecification() {
        String spec = "";

        // trying to read from file the specification...
        try {

            BufferedReader reader = new BufferedReader(new FileReader(filename));
            String line = reader.readLine();
            while(line!=null) {
                spec += line + "\n";
                line = reader.readLine();
            }        
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return spec;
    }



    String modelSpec = readSpecification();

我认为问题是读者找不到路径,因为它应该写成“C:\ Users \ MRx \ Desktop”,但是代码filename = f.getAbsolutePath(); 返回路径,如“C:\ Users \ Mrx \ Desktop .. 你有什么想法?谢谢你的帮助

编辑:这些是例外:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.io.FileInputStream.<init>(FileInputStream.java:116)
at java.io.FileInputStream.<init>(FileInputStream.java:79)
at java.io.FileReader.<init>(FileReader.java:41)
at TestPackage.MainFrame.readSpecification(MainFrame.java:333)
at TestPackage.MainFrame.<init>(MainFrame.java:349)
at TestPackage.MainFrame$8.run(MainFrame.java:323)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:672)
at java.awt.EventQueue.access$400(EventQueue.java:81)
at java.awt.EventQueue$2.run(EventQueue.java:633)
at java.awt.EventQueue$2.run(EventQueue.java:631)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:642)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

1 个答案:

答案 0 :(得分:1)

更新在构造对象时,即在选择文件之前,您正在调用readSpecification方法。移动线

String modelSpec = readSpecification();

进入openModelActionPerformed方法。

基于不完整信息的旧答案
FileNotFoundException的邮件应包含未找到的文件的名称。由于它不存在,程序必须使用空字符串""作为文件名,这也恰好是您为filename变量提供的默认值。这表明您可能正在使用本地变量进行此分配:

filename = f.getAbsolutePath();

确保使用正确的变量。

要验证,请在打开前检查您尝试打开的文件:

System.out.println("Trying to open ["+filename+"]");
BufferedReader reader = new BufferedReader(new FileReader(filename));