【问题标题】:FileNotFoundException JFleChooser and FileReader JAVAFileNotFoundException JFleChooser 和 FileReader JAVA
【发布时间】:2016-02-28 11:06:15
【问题描述】:

我一直在编写一个代码,该代码从 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)

【问题讨论】:

  • 这无法编译,请贴出你实际使用的相关代码。
  • C:\Users\MRx\Desktop 是一个目录,不能像普通文件一样打开它。你想做什么?
  • 这些是相关的部分。我认为问题出在 OpenModel 方法和 readSpecification 方法中。 new FileReader 找不到我在 openModelActionPerformed 方法中选择的文件。
  • 已编辑:f.getSelectedFile() 和 getAbsolutePath() 返回我(即 C:\Users\MRx\Destop\sample.txt"
  • 1) new FileReader(filename) 最好是.. new FileReader(f) 2) "..这些是相关的部分。我认为问题出在此处" 你的想法可能是错误的,大多数人不会仔细研究没有可运行代码的问题。如需尽快获得更好的帮助,请发帖 minimal reproducible exampleShort, Self Contained, Correct Example

标签: java swing java-io filenotfoundexception


【解决方案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));

【讨论】:

  • 使用 JOptionPane.showMessageDialog(filename),我得到的 dir 路径为“C:\Users\Mrx\Destop\sample.txt”,所以变量文件名实际上得到了所选文件的 absolutedPath。但是,仍然,如果我返回变量 spec,字符串是空的。
  • 请用您实际使用的代码更新问题。
猜你喜欢
  • 1970-01-01
  • 2013-09-28
  • 1970-01-01
  • 2011-06-09
  • 2011-03-07
  • 1970-01-01
  • 2019-10-03
  • 2013-04-03
  • 1970-01-01
相关资源
最近更新 更多