代码如下:

@org.junit.test
public void test055() throws ioexception {
file infile = new file("d:\\chrysanthemum.jpg");
fileinputstream fileinputstream = new fileinputstream(infile);
bytearrayoutputstream bytearrayoutputstream = new bytearrayoutputstream();
int i;
//转化为字节数组流
while ((i = fileinputstream.read()) != -1) {
bytearrayoutputstream.write(i);
}
fileinputstream.close();
// 把文件存在一个字节数组中
byte[] filea = bytearrayoutputstream.tobytearray();
bytearrayoutputstream.close();
string encoding = "iso-8859-1";
string fileastring = new string(filea, encoding);
system.out.println(fileastring);
// 写入文件
fileoutputstream fileoutputstream = new fileoutputstream("d:/b.png");
fileoutputstream.write(fileastring.getbytes(encoding));
fileoutputstream.flush();
fileoutputstream.close();
}
注意:
(1)使用bytearrayoutputstream 来把二进制流转化为字节数组流;
(2)把字节数组转化为string类型时,一定要使用iso-8859-1编码;
string encoding = "iso-8859-1";
string fileastring = new string(filea, encoding);
(3)通过字符串获取字节数组时,一定要使用iso-8859-1编码:
fileoutputstream.write(fileastring.getbytes(encoding));