【问题标题】:How to load files using relative path in NetBeans如何在 NetBeans 中使用相对路径加载文件
【发布时间】:2012-08-24 10:09:18
【问题描述】:
import java.io.*;
import java.util.Properties;

public class NewClass {
    public static void main(String args[]) throws IOException  {
        Properties p = new Properties();
        p.load(new FileInputStream("DBDriverInfo.properties"));
        String url=p.getProperty("url");
        String user=p.getProperty("username");
        String pass=p.getProperty("password");
        System.out.println(url+"\n"+user+"\n"+pass);
    }
}

虽然DBDriverInfo.properties文件在同一个目录下,但还是会出现如下异常。

Exception in thread "main" java.io.FileNotFoundException: DBDriverInfo.properties (The system cannot find the file specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:97)
    at NewClass.main(NewClass.java:7)

在命令行界面中使用javac 编译时,相对路径可以正常工作。 但在 NetBeans 中引发了异常。

【问题讨论】:

    标签: java netbeans properties netbeans-7 fileinputstream


    【解决方案1】:

    在 Netbeans 中,您需要将该文件放在项目文件夹中,而不是放在 src/package 文件夹中。

    【讨论】:

      【解决方案2】:

      您应该指定文件的完整路径或将文件放到项目目录中。项目目录是运行项目时的当前目录。

      【讨论】:

        【解决方案3】:

        确保您的 DBDriverInfo.properties 在 CLASSPATH 上。根据您的代码,将您的属性文件放置到 netbeans 的默认包中。

        【讨论】:

          【解决方案4】:

          File 类的默认目录是您开始执行主类的目录。对于这些 IDE,默认目录将是您的项目主目录。

          为了更好地了解您的默认目录,请在 IDE 中执行这两行代码。然后把你的文件放在那里。

          File f = new File("DBDriverInfo.properties");
          System.out.println(f.getAbsolutePath());
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2016-04-23
            • 2010-11-18
            • 1970-01-01
            • 2016-09-13
            • 2023-04-01
            • 2014-08-03
            相关资源
            最近更新 更多