从AssetManager读取文件作为InputStream后的java.lang.NullPointerException

时间:2011-08-09 08:43:44

标签: android

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的assets目录);

有什么原因吗?

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

1 个答案:

答案 0 :(得分:0)

你的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();