我正在尝试将密钥库作为资源读取。示例代码如下。我遇到的问题是inputStream保持为null。
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);
}
}
}
首先我认为这只是一个路径问题,但即使文件本身位于类旁边,我也无法加载它。
即使我使用绝对路径,结果也是一样的。
我犯的错是什么?
当您使用getClassLoader().getResourceAsStream("...")
时,它会尝试在类路径的根目录中找到该文件。尝试使用:
Security.class.getResourceAsStream("keePass.kdbx");
在这种情况下,它将尝试在与Security
类相同的位置找到该文件
查看更多What is the difference between Class.getResource() and ClassLoader.getResource()?