使用ByteArrayOutputStream写入字符串方式

网友投稿 660 2022-11-16

使用ByteArrayOutputStream写入字符串方式

使用ByteArrayOutputStream写入字符串方式

目录使用ByteArrayOutputStream写入字符串文件与二进制数据互转-ByteArrayOutputStream

使用ByteArrayOutputStream写入字符串

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

// 获取二进制数据

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 Bufferehttp://dOutputStream(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()的意义,原因:底层空实现(源码如下)

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:sqlite3学习笔记(一)Linux环境安装
下一篇:操作系统(三)进程
相关文章

 发表评论

暂时没有评论,来抢沙发吧~