【问题标题】:java.lang.NullPointerException after reading file as InputStream from AssetManager从 AssetManager 读取文件作为 InputStream 后的 java.lang.NullPointerException
【发布时间】:2011-08-09 08:43:44
【问题描述】:

AssetManager 定义及使用:

...
AssetManager mngr = getAssets();
try{
      encrypter.decrypt(mngr.open("sample.txt"),output_file);
}...(continued)

解密函数:

public void decrypt(InputStream in, OutputStream out)
    {
            try
            {
                    // Bytes read from in will be decrypted
                    in = new CipherInputStream(in, dcipher);
                    // Read in the decrypted bytes and write the cleartext to out
                    int numRead = 0;
                    while ((numRead = in.read(buf)) >= 0)
                    {
                      out.write(buf, 0, numRead);
                    }
                    out.close();
            ...(continued)

out.write(buf, 0, numRead); 行的错误是 java.lang.NullPointerException。

当用作以下调用时,此调用运行良好:

*encrypter.decrypt(new FileInputStream("sample.txt"),output_file)*(即从本地而不是android的资产目录读取文件时);

有什么原因吗?

任何帮助表示赞赏!谢谢!

【问题讨论】:

  • 显示完整代码,我的意思是声明
  • 声明哪一部分.. AssetManager?

标签: android


【解决方案1】:

你的 OutputStream 没有初始化。所以你得到空指针异常。你可能想要 像这样的

 public void decrypt(InputStream in,String file)
        {
                try
                {
                 OutputStream out = new FileOutputStream(file);
                        // Bytes read from in will be decrypted
                        in = new CipherInputStream(in, dcipher);
                        // Read in the decrypted bytes and write the cleartext to out
                        int numRead = 0;
                        while ((numRead = in.read(buf)) >= 0)
                        {
                          out.write(buf, 0, numRead);
                        }
                        out.close();

【讨论】:

  • 谢谢问题正是你所说的......非常感谢。
猜你喜欢
  • 2014-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-19
  • 2013-02-20
  • 2018-12-14
  • 1970-01-01
相关资源
最近更新 更多