本帖最后由 默默呜呜 于 2019-3-6 16:21 编辑
| 一 、ByteArrayInputStream和ByteArrayOutputStream(java I/O流---内存操作流) |
| ByteArrayInputStream包含一个内部缓冲区,该缓冲区包含从流中读取的字节,内部计数器跟着read方法要提供的下一个字节。FileInputStream是把文件当做数据源。ByteArrayInputStream则是把内存中的某一个数组单做数据源。ByteArrayOutputStream类实现了一个输出流。其中的数据被写入一个byte数组。缓冲区会随着数据的不断写入而自动增长。可使用toByteArray()和toString()获取数据源的。ByteArrayOutputStream将一个输出流指向一个Byte数组,但这个Byte数组是ByteArrayOutputStream内部内置的,不需要定义。 |
[mw_shl_code=java,true]import java.io.* ;
public class ByteArrayDemo01{
public static void main(String args[]){
String str = "HELLOWORLD" ; // 定义一个字符串,全部由大写字母组成
ByteArrayInputStream bis = null ; // 内存输入流
ByteArrayOutputStream bos = null ; // 内存输出流
bis = new ByteArrayInputStream(str.getBytes()) ; // 向内存中输出内容
bos = new ByteArrayOutputStream() ; // 准备从内存ByteArrayInputStream中读取内容
int temp = 0 ;
while((temp=bis.read())!=-1){
char c = (char) temp ; // 读取的数字变为字符
bos.write(Character.toLowerCase(c)) ; // 将字符变为小写
}
// 所有的数据就全部都在ByteArrayOutputStream中
String newStr = bos.toString() ; // 取出内容
try{
bis.close() ;
bos.close() ;
}catch(IOException e){
e.printStackTrace() ;
}
System.out.println(newStr) ;
}
};[/mw_shl_code] |
| 二、BufferedInputStream和BufferedOutputStream(Java I/O流---过滤流—缓冲流) |
| 类BufferedInputStream和BufferedOutputStream继承FilterInputStream和FilterOutputStream,实现了带缓冲的过滤流,它提供了缓冲机制,把任意的I/O流“捆绑”到缓冲流上,可以提高该I/O流的读取效率,在初始化时,除了要指定所连接的I/O流之外,还可以指定缓冲区的大小。在读写的同时对数据缓存,这样避免每次读写数据都要进行实际的物理读写操作,在用BufferdOutputStream输出时,数据先输入缓冲区,当缓冲区满的时再写入连接的输出流,可以调用flush()来清空缓冲区。这两个流是处理流,通过内部缓存数组来提高操作流的效率 |
[mw_shl_code=java,true] public void copyFile(String src , String dec){
FileInputStream fis=null;
BufferedInuptStream bis=null;
FileOutputStream fos=null;
BufferedOutputStream bos=null;
try {
fis=new FileInputStream(src);
fos=new FileOutputStream(dec);
bis=new BufferedInputStream(fis);
bos=new BufferedOutputStream(fos);
while ((temp=bis.read())!=-1) {
bos.write(temp);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally {
//增加处理流后,注意流的关闭顺序!“后打开的先关闭”
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}[/mw_shl_code] |
|
|