我是靠谱客的博主 追寻缘分,这篇文章主要介绍使用ByteArrayOutputStream写入字符串方式,现在分享给大家,希望可以做个参考。

使用ByteArrayOutputStream写入字符串

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.gk; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; /** * 使用ByteArrayOutputStream写入字符串 * @author GuoKe *说明:1,不关联源 2.可以不释放资源 3.使用toByteArray()获取数据 */ public class IOTest8 { public static void main(String[] args) { byte[] dest = null; ByteArrayOutputStream bs = null; try { bs = new ByteArrayOutputStream(); String str = "hello"; byte[] datas = str.getBytes(); bs.write(datas,0,datas.length); bs.flush(); dest = bs.toByteArray(); System.out.println(dest.length + ":" + new String(dest,0,dest.length/*bs.size()*/)); }catch(FileNotFoundException e){ e.printStackTrace(); }catch(IOException e){ e.printStackTrace(); }finally { try { if (bs != null) {//alt+shift+z bs.close(); } } catch (Exception e) { e.printStackTrace(); } } } }

文件与二进制数据互转-ByteArrayOutputStream

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// 获取二进制数据 public static byte[] getFileBinary(String filePath) { FileInputStream fis = null; BufferedInputStream bis = null; ByteArrayOutputStream baos = null; try { fis = new FileInputStream(filePath); bis = new BufferedInputStream(fis); baos = new ByteArrayOutputStream(); int c = bis.read(); while (c != -1) { // 数据存储到ByteArrayOutputStream中 baos.write(c); c = bis.read(); } fis.close(); bis.close(); // 转换成二进制 return baos.toByteArray(); } catch (Exception e) { e.printStackTrace(); } finally { // 没有关闭ByteArrayOutputStream流的意义,空实现 try { if (fis != null ) { fis.close(); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (bis != null ) { bis.close(); } } catch (IOException e) { e.printStackTrace(); } } } return null; } // 二进制数据转成文件 public static void binaryToFile(byte[] bytes, String filePath) { FileOutputStream fos = null; BufferedOutputStream bos = null; try { fos = new FileOutputStream(filePath); bos = new BufferedOutputStream(fos); bos.write(bytes); } catch (Exception e) { e.printStackTrace(); } finally { try { if (fos != null ) { fos.close(); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (bos != null ) { bos.close(); } } catch (IOException e) { e.printStackTrace(); } } } }

ByteArrayOutputStream没有执行close()的意义,原因:底层空实现(源码如下)

以上为个人经验,希望能给大家一个参考,也希望大家多多支持靠谱客。

最后

以上就是追寻缘分最近收集整理的关于使用ByteArrayOutputStream写入字符串方式的全部内容,更多相关使用ByteArrayOutputStream写入字符串方式内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(132)

评论列表共有 0 条评论

立即
投稿
返回
顶部