2

我有一个 Eclipse Web 项目。我在根目录中有一个名为 deploy.properties 的文件,似乎没有被读取。我有一种感觉,我可能需要将文件添加到“构建路径”(如 jar),但这只是一个猜测,当我尝试这样做时,没有将文件添加到构建路径的选项,这样让我觉得我错了。

89号线就是这个props.load(stream);

我的堆栈跟踪如下所示:

java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:365)
at java.util.Properties.load(Properties.java:293)
at sempedia.dao.Dao.getConfigFile(Dao.java:89)
at sempedia.dao.Dao.<clinit>(Dao.java:17) 89 

这个类看起来像这样:

public class Dao {
private static final String configFileLocation = "/deploy.properties";

private static final Properties configFile = getConfigFile(configFileLocation);

private static final String host = configFile.getProperty("mysql.host");
private static final String port = configFile.getProperty("mysql.port");
private static final String db   = configFile.getProperty("mysql.db");
private static final String user = configFile.getProperty("mysql.user");
private static final String pwd  = configFile.getProperty("mysql.pwd");

public static String getHost() { return host; }

public static String getPort() { return port; }

public static String getDb() { return db; }

public static String getUser() { return user; }

public static String getPwd() { return pwd; }


public static Connection getCon() {
    Connection con = null;
    try {
        String url = "jdbc:mysql://" + host + ":" + port + "/" + db;
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        con = DriverManager.getConnection(url, user, pwd);

    } catch (SQLException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return con;
}

private static Properties getConfigFile(String fileName) {
    Properties props = new Properties();
    try {
        InputStream stream = Dao.class.getResourceAsStream(fileName);
        props.load(stream);
    } catch (IOException e) {
        System.err.println("Error opening configuration file");
        System.exit(1);
    }

    return props;
}
}
4

2 回答 2

2

请记住,当您在 eclipse 项目中读取文件时,默认位置在您的源目录中(如果这是一个 Web 应用程序,稍后将转换为您的 classes 目录)。所以我的建议是尝试将文件从项目根目录移动到您的“src”目录并重试。

于 2011-05-16T07:48:53.913 回答
0

如果类路径中不存在目标文件,则方法 Dao.class.getResourceAsStream(fileName) 将 null 作为输入流返回 - 这就是 NullPointerException 的原因。

您应该在调用 props.load(stream) for null 之前捕获它(现在您只捕获 IOException)或测试输入流;

现在你的意思是什么根目录?系统根目录、应用程序源根目录、应用程序工作目录?系统根目录是放置配置文件的一个相当糟糕的地方。

使用“deploy.properties”(开头没有斜杠)解决它,并将其放在类路径的根目录中(“classes”、“bin” - 或任何你称之为的)。

如果将它放在源目录的默认包级别 - 无论是在源目录中,还是在您添加为源目录的目录中,它将在编译期间复制到类路径中,如下所示:

/app
  /src
  /config
    deploy.properties 

现在将 config 目录作为源目录添加到项目中。

于 2011-05-16T07:55:34.553 回答