Java 没有得到这样的文件或目录
我需要打开、读取并获取.pfx文件的路径。该文件位于我的android studio项目文件夹MyApp/certificate/mycertificate.pfx中Java 没有得到这样的文件或目录,java,android,certificate,pfx,chilkat,Java,Android,Certificate,Pfx,Chilkat,我需要打开、读取并获取.pfx文件的路径。该文件位于我的android studio项目文件夹MyApp/certificate/mycertificate.pfx中 public void openFile(){ CkCert cert = new CkCert(); File file = new File("/certificate/mycertificate.pfx"); String pfxFilename = file.getAbsolutePath();
public void openFile(){
CkCert cert = new CkCert();
File file = new File("/certificate/mycertificate.pfx");
String pfxFilename = file.getAbsolutePath();
String pfxPassword = "1234";
cert.LoadPfxFile(pfxFilename,pfxPassword)};
我得到以下错误:没有这样的文件或目录。有什么建议吗
已解决:
我将文件移动到\app\src\main\assets
public void open(Context context){
InputStream cert= context.getAssets().open("mycert.pfx");
char[] password = null;
KeyStore keystore = null;
Enumeration<String> aliases;
String alias = "";
//open the file
senha = "1234".toCharArray();
keystore = KeyStore.getInstance("PKCS12");
keystore.load(cert, password);
//Get the alias
KeyStore.PrivateKeyEntry pkEntry = null;
PrivateKey pk = null;
try {
aliases = keystore.aliases();
while(aliases.hasMoreElements()) {
alias = aliases.nextElement();
System.out.println(alias);
if (keystore.isKeyEntry(alias)) {
pkEntry = (KeyStore.PrivateKeyEntry) keystore.getEntry(alias, new KeyStore.PasswordProtection(password));
pk = pkEntry.getPrivateKey();
}
}
} catch (KeyStoreException e) {
throw new RuntimeException("CATCH", e);
}
public void open(上下文){
InputStream cert=context.getAssets().open(“mycert.pfx”);
char[]password=null;
密钥库KeyStore=null;
枚举别名;
字符串别名=”;
//打开文件
senha=“1234”。toCharArray();
keystore=keystore.getInstance(“PKCS12”);
keystore.load(证书、密码);
//获取别名
KeyStore.PrivateKeyEntry pkEntry=null;
PrivateKey pk=null;
试一试{
别名=密钥库。别名();
while(别名.hasMoreElements()){
别名=别名.nextElement();
System.out.println(别名);
if(keystore.isKeyEntry(别名)){
pkEntry=(KeyStore.PrivateKeyEntry)KeyStore.getEntry(别名,newkeystore.PasswordProtection(password));
pk=pkEntry.getPrivateKey();
}
}
}捕获(KeyStoreException e){
抛出新的RuntimeException(“CATCH”,e);
}
}
它只在我的android studio项目的根文件夹中
该文件位于开发计算机上,而不是任何设备上。相反,将其打包为模块的资产(
src/main/assets/
),并使用AssetManager
打开该资产上的InputStream
。新文件(“mycertificate.pfx”)
没有指向任何有意义的地方。此文件在用户设备上的具体位置?尚未在任何设备中。它只在我的android studio项目的根文件夹中。MyApp/certificate/mycertificate.pfx。我尝试了File File=new File(“/certificate/mycertificate.pfx”),但仍然收到相同的错误。但是你的应用程序正在你的Android设备上运行。你在城里。你永远不会没有电话。那它怎么能在你的电脑上找到文件呢!?在我的设备上运行应用程序不会自动获得它需要的所有东西[类、库、文件、img等等]?类似这样的东西?输入流证书;certificate=getClass().getResourceAsStream(“mycertificate.pfx”)@蒂托:不,类似于getAssets().open(“mycertificate.pfx”)
getAssets()
是Context
上的一个方法。InputStream certificate=getApplicationContext().getAssets().open(“mycertificate.pfx”);现在我得到了W/System.err:java.lang.NullPointerException:尝试在空对象上调用虚拟方法“android.content.Context android.content.Context.getApplicationContext()”reference@Tito:您可能正在尝试从字段初始值设定项执行此操作。在活动或服务的super.onCreate()
之后,才尝试使用getApplicationContext()
(此处不需要)或getAssets()
。