Byte存储为String时遇到的问题

来源:互联网 发布:情侣装店铺推荐知乎 编辑:程序博客网 时间:2024/06/05 19:18

做App时,每当节假日,公司都会要求更换启动图,如果不更改其它功能的话,再打包个APP发布到线上是完全多余的事情,想到可以利用数据存储流来处理图片,这里做个记录

//请求网络接口获取启动图,将图片转为流式@Overridepublic void onSuccess(File result_img){    byte [] mByte = getByte(result_img);    //将得到的byte[]转为Sting并放入SharePreference里    SharedPreferences sharedPreferences = getSharedPreferences("fileIO", MODE_PRIVATE);        SharedPreferences.Editor editor = sharedPreferences.edit();        try {        //ISO-8859-1为国际通用编码,用以正确的存储流            editor.putString("dex_startImage", new String(mByte, "ISO-8859-1"));            editor.commit();            //这里我们进行取流操作            sharedPreferences = getSharedPreferences("fileIO", MODE_PRIVATE);            String fileIOString = sharedPreferences.getString("dex_startImage", "");            byte[] asd_byte = fileIOString.getBytes("ISO-8859-1");    //将byte转为bitmap再转为BitmapDrawable            BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(), BitmapFactory.decodeByteArray(asd_byte, 0, asd_byte.length));            (LinearLayout)findviewbyId(R.id.mainactivity_linearLayout).setBackground(bitmapDrawable);        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        }}//图片文件转为流public byte[] getBytes(File file) {        byte[] buffer = null;        try {            File mFile = file;            FileInputStream fis = new FileInputStream(mFile);            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);            byte[] b = new byte[1024];            int n;            while ((n = fis.read(b)) != -1) {                bos.write(b, 0, n);            }            fis.close();            bos.close();            buffer = bos.toByteArray();        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        return buffer;    }}

非常简单,值得注意的就是存取byte时要设置编码标准,不然默认String是无法全部识别byte的

0 0