Java 密钥库未从文件初始化

Java 密钥库未从文件初始化,java,android,Java,Android,当我尝试加载(KeyStore方法)以前保存在KeyStore中的数据时,我收到eofeexception。创建文件并在其中保存数据(密钥库中的存储方法)。我想知道我应该在代码中更改什么以从文件中获取数据。 保存(创建文件、创建条目等): 装载: private void initializeKeyStore(Context context, int pin) { InputStream inputStream = null; try {

当我尝试加载(KeyStore方法)以前保存在KeyStore中的数据时,我收到
eofeexception
。创建文件并在其中保存数据(密钥库中的存储方法)。我想知道我应该在代码中更改什么以从文件中获取数据。 保存(创建文件、创建条目等):

装载:

  private void initializeKeyStore(Context context, int pin) {
        InputStream inputStream = null;
        try {
            mKeyStore = KeyStore.getInstance("BKS");
            File file = new File(context.getFilesDir().getAbsolutePath(), KEYSTORE_NAME);
            if (!file.exists()) {
                file.createNewFile();
            }
            inputStream = new FileInputStream(file);
            BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder total = new StringBuilder();
            String line;
            while ((line = r.readLine()) != null) {
                total.append(line);
            }
            mKeyStore.load(inputStream, (pin + "").toCharArray());
        }catch(...exceptions){}
  • newfileoutputstream()
    之前调用
    File.createNewFile()
  • newfileinputstream()之前调用它肯定会适得其反。它所完成的只是将
    FileNotFoundException
    转换为
    eofeexception。
  • 在这里,
    ByteArrayOutputStream
    也是毫无意义和浪费的,而且
    about
    在测试时不可能为空。直接写入文件即可
  • 您得到的
    EOFException
    可能意味着文件是空的,这反过来可能意味着
    newfileoutputstream(…)
    抛出了一个您没有注意到的异常,或者您根本就没有调用过它,直到您在打开它进行输入之前毫无意义地创建了它,文件才存在
不要这样写代码。我建议你把这些都修好,然后重新测试。我毫不怀疑你在这里报告的问题会消失。另一个问题很可能会浮出水面,目前被这一切所掩盖

  private void initializeKeyStore(Context context, int pin) {
        InputStream inputStream = null;
        try {
            mKeyStore = KeyStore.getInstance("BKS");
            File file = new File(context.getFilesDir().getAbsolutePath(), KEYSTORE_NAME);
            if (!file.exists()) {
                file.createNewFile();
            }
            inputStream = new FileInputStream(file);
            BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder total = new StringBuilder();
            String line;
            while ((line = r.readLine()) != null) {
                total.append(line);
            }
            mKeyStore.load(inputStream, (pin + "").toCharArray());
        }catch(...exceptions){}