从控制台运行java swing应用程序时出错

时间:2017-08-02 21:45:51

标签: java swing maven embedded-resource filenotfoundexception

我正在使用Java Swing应用程序,当我在IDE外部运行应用程序时(即在预生产中),我遇到了一个奇怪的错误。顺便说一下,我正在使用Netbeans 8.2。

应用程序连接到数据库并从connection.properties中的src/main/resources文件中获取配置属性,该文件当然包装在jar中的根目录中。

我能够编译应用程序并从Netbeans运行它没有问题:加载属性,完成与DB的连接,并根据业务逻辑等读取和更新数据。

当我尝试从控制台运行我的应用程序时出现问题。从那里我跑

java -jar myapp-1.0.jar

并收到以下错误

ago 01, 2017 8:41:25 PM ar.edu.unt.jdbc.GestorJdbc loadPropertiesFromFile
SEVERE: File not found
java.io.FileNotFoundException: file:/path/to/my/app/target/myapp-1.0.jar!/connection.properties (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at ar.edu.unt.jdbc.JdbcManager.loadPropertiesFromFile(JdbcManager.java:216)
... etc

但是,该文件确实存在。该方法的代码如下:

public class JdbcManager {

    static final String JDBC_DRIVER_PROPERTY = "jdbc.driver";
    static final String JDBC_URL_PROPERTY = "jdbc.url";
    static final String JDBC_USER_PROPERTY = "jdbc.username";
    static final String JDBC_PASSWORD_PROPERTY = "jdbc.password";
    String PROPERTIES_FILE_PATH = "connection.properties";

    private static final Logger LOGGER = Logger.getLogger(JdbcManager.class.getName());

    // This method is being called with PROPERTIES_FILE_PATH as a parameter
    // from another method in the same class
    Properties loadPropertiesFromFile(String configFilePath) {
        ClassLoader classLoader = getClass().getClassLoader();
        File configFile = new File(classLoader.getResource(configFilePath).getFile());
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(configFile));
            LOGGER.log(Level.INFO, "Properties loaded: {0}", properties);
        } catch (FileNotFoundException ex) {
            LOGGER.log(Level.SEVERE, "File not found", ex);
        } catch (IOException ex) {
            LOGGER.log(Level.SEVERE, "Error reading file", ex);
        }

        return properties;
    }
}

正如我所说,从Netbeans中可以正确读取文件。我在这做错了什么?提前感谢您的回答。

0 个答案:

没有答案