【问题标题】:Getting a file as a resource on classpath获取文件作为类路径上的资源
【发布时间】:2019-03-11 11:53:12
【问题描述】:

我正在尝试将密钥库作为资源读取。下面的示例代码。我遇到的问题是 inputStream 仍然为空。

import java.io.InputStream;

import java.util.List;

import org.linguafranca.pwdb.kdbx.KdbxCreds;
import org.linguafranca.pwdb.kdbx.simple.SimpleDatabase;
import org.linguafranca.pwdb.kdbx.simple.SimpleEntry;
import org.linguafranca.pwdb.Credentials;

import org.apache.log4j.Logger;



public class Security {

private static final String PATH = null;
private static final String KEYSTORE_PASSWORD = "admin";
static List<SimpleEntry> entries = null;

final static Logger logger = Logger.getLogger(Security.class);

public Security(){


    //TODO: initialize security and it's passwords


}

public static void init(){

try {

        //InputStream inputStream = new FileInputStream(".keePass.kdbx");
        InputStream inputStream = Security.class.getClassLoader().getResourceAsStream("keePass.kdbx");

        // password credentials
        Credentials credentials = new KdbxCreds(KEYSTORE_PASSWORD.getBytes());

        SimpleDatabase database = SimpleDatabase.load(credentials, inputStream);
        // Jaxb implementation seems a lot faster than the DOM implementation
        // visit all groups and entries and list them to console
        entries = database.getRootGroup().getEntries();

    }catch(Exception exception){
        logger.error(exception);
    }

}
}

首先我认为这只是路径问题,但是即使文件本身位于类旁边,我也无法加载它。

即使我使用绝对路径,结果也是一样的。

我犯了什么错误?

【问题讨论】:

  • 您的文件位于源路径中。但它在类路径中吗? (编译的 .class 火灾在哪里)你在使用 maven 吗?
  • 确实是这个问题,我没有把合适的文件夹放到运行配置中。

标签: java inputstream keepass


【解决方案1】:

当您使用getClassLoader().getResourceAsStream("...") 时,它会尝试在类路径的根目录中查找文件。尝试使用:

Security.class.getResourceAsStream("keePass.kdbx");

在这种情况下,它将尝试在与 Security 类相同的位置查找文件

查看更多What is the difference between Class.getResource() and ClassLoader.getResource()?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-09
    • 2020-09-09
    • 1970-01-01
    • 2010-10-22
    • 1970-01-01
    • 1970-01-01
    • 2015-05-02
    相关资源
    最近更新 更多