Android: compile error Util.toByteArray (taken from an example)

試著忘記壹切 提交于 2019-12-02 07:33:39

问题


I am trying to compile this sample of code in my Android app to have crypt/decrypt feature. I found that code here http://apachejava.blogspot.it/2012/04/androidencryption-made-easy.html I don't know if it's good but that's not relevant here.

When compiling it's all OK but Util.toByteArray produces this error "Util cannot be resolved". Replacing Util with Utils is not any useful.

Any help?


回答1:


Part of the needed code is missing in the page you link : the author forgot to show his Util class which obviously contains a toByteArray function.

Solution 1 : use commons IO

Replace

Util.toByteArray(cis);   

by

IOUtils.toByteArray(cis);

IOUtils is a Apache commons IO utility class.

You'll need

  • to download the commons IO jar (see link) and set your classpath accordingly
  • this import at the start of your class : import org.apache.commons.io.IOUtils;

Solution 2 : write a toByteArray function

Define this function :

public byte[] toByteArray(InputStream is) throws IOException {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int l;
    byte[] data = new byte[1024];
    while ((l = is.read(data, 0, data.length)) != -1) {
      buffer.write(data, 0, l);
    }
    buffer.flush();
    return buffer.toByteArray();
}

And replace Util.toByteArray(cis); by toByteArray(cis);.



来源:https://stackoverflow.com/questions/11540018/android-compile-error-util-tobytearray-taken-from-an-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!