1. 今天遇到个IO操作中的优化,感谢我们总监的给力,发现了这个问题。
一般来说,这个优化只要百度一下,网上一大遍,所以过多重覆的我就不提了,主要是重点。
很多时候,我们在读IO的时候,有可能会对字节进行加密处理或者加密保存,当我接受这个需求开发的时候,
就直接这样写:
<span style="font-family:Courier New;font-size:18px;">private boolean byte2File(byte[] bytes,FileOutputStream out) {
if(bytes==null||bytes.length==0||out==null)
return false;
try {
for (int i = 0; i <bytes.length; i++) {
out.write((byte) (bytes[i] ^ Constants.encode_key));
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}</span>
后来发现这样读流的时候,在写入文件中的时候,会变得好慢,即使是在异步来处理这个加密,但这个操作在处理大文件的时候就变得异常的慢,
由于客户端并没有太多的大数据,只有一个截图是比较大,每当加载它的时候就会变得异常的慢,后来总监在审查代码时候,帮我改为:
<span style="font-family:Courier New;font-size:18px;"> private boolean byte2Filewithencoded(byte[] bytes,FileOutputStream out){
if(bytes==null||bytes.length==0||out==null)
return false;
byte[] header = new byte[4];
for (int i = 0; i < 4;i++) {
header[i] = 0x0f;
}
try {
out.write(header);
byte[] buffer = new byte[4 * 1024];
// for (int i = 0; i <bytes.length; i++) {
// out.write((byte) (bytes[i] ^ Constants.encode_key/*[index++ % size]*/));
// }
int offset = 0;
int count = 0;
while ((count = copyByteData(bytes, buffer, offset)) > 0) {
for (int i = 0; i< count; i++) {
buffer[i] = (byte) (buffer[i] ^ Constants.encode_key);
}
out.write(buffer, 0 , count);
offset += count;
}
out.flush();
// out.close();
} catch (IOException e) {
e.printStackTrace();
Logger.d("BitmapLoader-----------byte2File------IOException---");
} finally {
try {
out.close();
} catch (Exception e){}
}
return true;
}
private int copyByteData(byte[] src, byte[] des, int offset) {
int i = 0;
for (; i < des.length && (i + offset) < src.length; i++) {
des[i] = src[i + offset];
}
return i;
}</span>
原来很简单,先复制一份源字节buffer,用于加密,后再继续读流。由于buffer的缓冲机制很好,所以该方法在写入文件的时候也有了质的提升。
希望对大家有用。