字节流转化为文件流_字节流转成字符串之后,在通过字符串转成字节流后的文件为什么会不一样?...

public static void main(String[] args) throws Exception {

File sourceFile = new File("/home/joy/图片/img1-lg.jpg");

File tempFile = new File("/home/joy/桌面/TempFile");

saveTempFile(sourceFile, tempFile);

String str = byteToString(tempFile);

File saveFile = new File("/home/joy/桌面/saveFile.jpg");

StringTobyte(str,saveFile);

}

// 保存临时文件

public static void saveTempFile(File sourceFile, File tempFile) throws Exception {

FileInputStream inputStream = new FileInputStream(sourceFile);

FileOutputStream fileOutputStream = new FileOutputStream(tempFile);

byte[] buf = new byte[10 * 1024];

int readLeng = 0;

while ((readLeng = inputStream.read(buf)) != -1) {

fileOutputStream.write(buf, 0, readLeng);

fileOutputStream.flush();

}

fileOutputStream.close();

inputStream.close();

}

// 文件字节转字符串

public static String byteToString(File file) throws Exception {

StringBuilder returnDatas = new StringBuilder();

FileInputStream fileInputStream = new FileInputStream(file);

byte[] buf = new byte[10 * 1024];

int readLenth = 0;

while ((readLenth = fileInputStream.read(buf)) != -1) {

returnDatas.append(new String(buf,0,readLenth));

}

fileInputStream.close();

return returnDatas.toString();

}

// 字符串转文件

public static void StringTobyte(String str,File file) throws Exception {

FileOutputStream fileOutputStream = new FileOutputStream(file);

fileOutputStream.write(str.getBytes());

fileOutputStream.close();

}

代码大意:把一张图片通过字节流转成一个字符串,然后在获取该字符串的字节后还原为文件。

理解中,字符只是多带一层编码,还原成字节后应该还是能获取到源文件的呀。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值