代碼如下:
@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));