Java_139_IO_字节数组流_ByteArrayInputStream&ByteArrayOutputStream
·
字节数组输入流
package IOStudy;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* 字节数组
* 1.源头换成字节数组
* 2.字节数组流不用关,保证风格统一关了也没事
* 3.任何东西都可以转成字节数组
* 4.字节数组不要太大
*
* 字节数组输入流
* 1.创建源:字节数组不要太大
* 2.选择流
* 3.操作
* 4.释放资源
* @author pmc
*
*/
public class ByteArrayIO {
public static void main(String[] args){
//1.创建源
byte[] src="talk is cheap show me the code".getBytes();
//2.选择流
InputStream is=null;
is=new ByteArrayInputStream(src);
//3.操作 分段读取
byte[] flush=new byte[5];
int len=0;//接收长度
try {
while((len=is.read(flush))!=-1){
String str=new String(flush,0,len);
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
字节数组输出流
package IOStudy;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* 字节数组
* 1.源头换成字节数组
* 2.字节数组流不用关,保证风格统一关了也没事
* 3.任何东西都可以转成字节数组
* 4.字节数组不要太大
*
* 字节数组输出流ByteArrayOutputStream
* 1.创建源:内部维护
* 2.选择流:不关联源
* 3.操作(写出内容)
* 4.释放资源:可以不用
*
* 获取数据:toByteArray() 返回byte[]数组
* @author pmc
*
*/
public class ByteArrayIOout2 {
public static void main(String[] args){
//1.创建源,字节数组输出流不用创建源,为保持风格统一用null.
byte[] dest=null;
//2.选择流(新增方法)
ByteArrayOutputStream out=null;
out=new ByteArrayOutputStream();
//3.操作(写出)
String msg="show me the code";
byte[] datas=msg.getBytes();
try {
out.write(datas);
out.flush();
dest=out.toByteArray();
System.out.println(dest.length+"--"+new String(dest,0,out.size()));
}catch (IOException e) {
e.printStackTrace();
}finally{
if(out!=null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
更多推荐


所有评论(0)