【问题标题】:Get StreamCorruptedException when I try to read cripted object from a file当我尝试从文件中读取 cripted 对象时获取 StreamCorruptedException
【发布时间】:2014-05-11 05:57:38
【问题描述】:

当我尝试读取存储在文件中的 cripted 对象时,显然一切正常 并且我可以获得保存的值,但在日志中总是出现此错误

 java.io.StreamCorruptedException
W/System.err﹕ at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:2067)
W/System.err﹕ at java.io.ObjectInputStream.<init>(ObjectInputStream.java:372)

我不明白如何解决它

我用这个来加载:

ObjectInputStream inputStream = null;
        try {
            inputStream = new ObjectInputStream(cipherInputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (inputStream != null) {

            try {
                myDecipheredObject = (Serializable) inputStream.readObject();


            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

这个要存储

 ObjectOutputStream outputStream = null;
            try {
                outputStream = new ObjectOutputStream(cipherOutputStream);
                outputStream.writeObject(object);
                outputStream.close();

            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (RuntimeException e) {
            e.printStackTrace();
        }

错误发生在这行加载方法中

inputStream = new ObjectInputStream(cipherInputStream);

【问题讨论】:

  • 你能展示你用来创建密码输入和输出流的代码吗?
  • 我在其他各种方法中使用了与此处使用的密码相同的代码,但此错误只发生在这里,所以我几乎可以肯定问题的原因是另一个。

标签: java android file-io fileinputstream fileoutputstream


【解决方案1】:

在您指定的行中,我能想到的唯一可能的异常原因是:

当您从另一个 InputStream 构造一个新的 ObjectInputStream 时,构造函数会尝试从另一个 InputStream 读取一个标头。如果它无法读取和验证此标头,则会引发 StreamCorrupted 异常。如果它无法读取标头,或者标头错误(例如,包含不同的幻数或版本号),就会发生这种情况。

是否有可能在输入流尝试从中读取之前实际上并未创建相应的输出流?或者两个不同的线程都试图从 cipherOutputStream 中读取数据?

如果对象的写入需要很长时间,那么可能值得在构造它之后直接刷新 outputStream,以便至少立即写入标头:

            outputStream = new ObjectOutputStream(cipherOutputStream);
            outputStream.flush();
            outputStream.writeObject(object);
            outputStream.close();

最后,我假设您使用与加密相同的密钥进行解密。如果不是,那么这可能会导致标头被错误地解密。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-05
    相关资源
    最近更新 更多