简体   繁体   中英

Getting a file as a resource on classpath

I'm trying to read a keystore as a resource. Sample code below. The problem I'm running into is that inputStream remains 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);
    }

}
}

First I thought it's just a matter of path, however even though the file itself resides next to the classes, I can't load it.

在此处输入图片说明

Even if I use absolute path, result is the same.

What is the mistake I'm making?

When you are using getClassLoader().getResourceAsStream("...") it tries to find the file in the root of classpath. Try to use:

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

In this case it will try to find the file in the same location as the Security class

See more What is the difference between Class.getResource() and ClassLoader.getResource()?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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