日志文章

2019-12-23 aflfte2011

IO字节数组输入流与输出流的使用

package com.aflfte.IO;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;


/**
 * 字节数组输入流
 * @author jinhao
 * 1、创建源:字节数组不要太大
 * 2、选择流
 * 3、操作
 * 4、释放资源(字节流操作可有可无)
 * 
 */
public class Test09 {
public static void main(String[] args) {
byte[] src="Talk is cheap show me the code".getBytes();
InputStream is=new ByteArrayInputStream(src);
byte[] flush=new byte[5];
int len=-1;
try {
while((len=is.read(flush))!=-1) {
String str=new String(flush,0,len);
System.out.println(str);
}
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}

package com.aflfte.IO;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 字节数组输出流
 * @author jinhao
 * 1、创建源:系统内部维护
 * 2、选择流:不关联源
 * 3、操作(写入内容)
 * 4、释放资源(字节数组操作可有可无)
 * 
 * 获取内容使用:toByteArray();
 *
 */
public class Test10 {
public static void main(String[] args) {
//创建源(可有可无)
byte[] dest=null;
//选择流(新增方法)
ByteArrayOutputStream baos=null;
baos=new ByteArrayOutputStream();
String msg="show me the code";
byte[] datas=msg.getBytes();
baos.write(datas,0,datas.length);
try {
baos.flush();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
dest=baos.toByteArray();
System.out.println(dest.length+"-->"+new String(dest,0,baos.size()));

}
}


« 利用IO字节数组流实现文件拷贝 | 文本文件的读写(Reader,Wirter的使用)»