在NetBeans下写了断代码测试了下:  
    文件结构: 
    Main.java 
  res/th.mid 源码如下: 
public class Main { 
    public static void main(String[] args) { 
        File f = new File("res/th.mid"); 
        if (f.exists()){ 
            System.out.println("true"); 
        }else { 
            System.out.println("false"); 
        } 
    } } 在netBeans下运行文件,结果为false; 
在命令行中找到build/classes目录,运行结果为true; 如何在Netbeans中设置可以得到CMD下运行的结果。

解决方案 »

  1.   

    又:
    通过测试项目dist目录下的jar文件,运行结果为false
    将jar文件用winrar解压,用java命令运行class文件结果为true,奇怪!
      

  2.   

    和你的运行记录有关. 
    NetBeans中的运行目录是project的根目录, 而不是build/class这个classpath目录. File f = new File(Main.class.getResource("res/th.mid").getFile());
    System.out.println(f.getAbsolutePath() + ":" + f.exists());
      

  3.   


    测试了一下,eclipse也是这样。
      

  4.   


    运行时抛出异常:
    Exception in thread "main" java.lang.NullPointerException
    指示语句File f = new File(Main.class.getResource("res/th.mid").getFile()); 
    说明依然无法找到文件如改为:File f = new File(Main.class.getResource("/res/th.mid").getFile()); 
    则结果为false
      

  5.   

    System.out.println(f.getAbsolutePath() + ":" + f.exists());路径是正确的,结果还是false
      

  6.   

    Eclpise中测试了一下:File f = new File(Main.class.getResource("/res/th.mid").getFile()); 
    System.out.println(f.getAbsolutePath() + ":" + f.exists()); 
    结果为true为什么在Neatbeans中却为false