番石榴函数toByteArray()返回null?

时间:2016-03-23 23:04:33

标签: java android android-studio guava

这是我的代码段:

File file = new File("encryptedImageFileName");
byte[] encryptedBytes = null;
try
{
    encryptedBytes = Files.toByteArray(file);
}
catch (Exception e)
{}

在我使用调试器后,这里有两个变量 encryptedBytes file 的图片,

http://i.stack.imgur.com/5nJgs.png

我几乎可以肯定文件下的所有内容都意味着它实际上找到了该文件,但正如您所看到的那样 encryptedBytes 为空,所以 Files.toByteArray(文件)没有工作......为什么会这样?

********************************** EDIT ************ ********************

这是我尝试编写字节数组的代码,它有什么问题吗?

FileOutputStream outputStream;
try
{
    outputStream = openFileOutput("encryptedImageFileName", Context.MODE_PRIVATE);
    outputStream.write(encodedByteArrayImage);
    outputStream.close();
}
catch (Exception e)
{
    e.printStackTrace();
}

抛出

java.io.FileNotFoundException: encryptedImageFileName: open failed: ENOENT (No such file or directory) 

调试器表示 encodedByteArrayImage 具有(非空)值。

2 个答案:

答案 0 :(得分:3)

不。您可以创建一个实际上不存在于文件系统中的new File,并且无法正常打开,然后当您尝试从中读取时,您将获得IOException,这看起来像这里发生了什么。

尝试使用e.printStackTrace()找出抛出的异常以及原因。

答案 1 :(得分:0)

我解决了,

这里是要编写的代码:

try
    {
        File file = new File(this.getFilesDir().getPath() + "encryptedImageFileName.txt");
        ByteSink sink = Files.asByteSink(file);
        sink.write(encryptedBytes);
    }
catch (Exception e)
    {
        e.printStackTrace();
    }

这里的代码是:

encryptedBytes = null;
try
    {
        File file = new File(this.getFilesDir().getPath() + "encryptedImageFileName.txt");
        ByteSource source = Files.asByteSource(file);
        encryptedBytes= source.read();
    } 
catch (Exception e)
    {
        e.printStackTrace();
    }

在使用ByteSink而不是我之前写的内容之后,我收到了一个只读错误,因为我试图写入root而不是app目录,我错过了这个:

this.getFilesDir().getPath() + 

在文件名之前(在名称的末尾添加了.txt)。