繁体   English   中英

如何使用NetBeans中的相对路径加载文件

[英]How to load files using relative path in NetBeans

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中的异常引发了异常。

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

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

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

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

要更好地了解您的默认目录,请从IDE执行这两行。 然后将文件放在那里。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM