【问题标题】:why does getResource give different result?为什么 getResource 会给出不同的结果?
【发布时间】:2012-06-09 01:18:18
【问题描述】:

Bellow 是我的代码,当我在 IDE 中运行这些代码时,它运行良好,但是当我在 dos 命令中运行时,它给我一个 NullPointException 错误。请帮我一把。 谢谢!

     //first get the classLoader
    ClassLoader classLoader = TestMainPath.class.getClassLoader();
    //show message
    System.out.println("loader=" + classLoader);
    //
    URL r = classLoader.getResource("TestMainPath/TestMainPath.class");
    System.out.println("r=" + r);
    String mainPath =r.getPath();
    System.out.println(mainPath);
    File sf = new File(mainPath + "/main/newfile");
    System.out.println(sf.getPath());
    System.out.println(sf.exists());

【问题讨论】:

  • 哪一行有 NullPointerException?
  • 我认为你得到NullPointerException 的那一行是:String mainPath = r.getPath() - 这表明类加载器没有找到这个文件。这可能是类路径问题。

标签: java getresource


【解决方案1】:

您的问题只是因为您的 IDE 没有像您一样启动应用程序。在您的情况下,区别在于类路径。 检查你的 IDE 如何启动你的程序,它使用哪个类路径。当您从命令行启动时,还要验证您的类文件是否真的在您期望的位置。

【讨论】:

    猜你喜欢
    • 2014-02-01
    • 2021-08-26
    • 1970-01-01
    • 2015-11-16
    • 2010-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-17
    相关资源
    最近更新 更多