您的位置:首页 > 编程语言 > PHP开发

关于ByteArrayOutputStream(字节数组输出流)的一个例子,与ByteArrayInputStream作一比较

2007-07-20 13:18 537 查看

import java.io.*;






public class ByteArrayOutputStreamDemo ...{






/** *//**


* ByteArrayOutputStream是一个把字节数组当作输出流的实现。我认为是所流当作数组来实现.它和ByteArrayInputStream不太一样。不能类比学习.


*


* java.lang.Object


继承者 java.io.OutputStream


继承者 java.io.ByteArrayOutputStream




所有已实现的接口:


Closeable, Flushable




public class ByteArrayOutputStream


extends OutputStream




此类实现了一个输出流,其中的数据被写入一个字节数组。缓冲区会随着数据的不断写入而自动增长。可使用 toByteArray() 和 toString() 检索数据。




关闭 ByteArrayOutputStream 无效。在关闭此流后且没有生成 IOException 时,可以调用此类中的该方法。


*


* 构造方法摘要


ByteArrayOutputStream()


创建一个新的字节数组输出流。


ByteArrayOutputStream(int size)


创建一个新的字节数组输出流,它具有指定大小的缓冲区容量(以字节为单位)。


* 字段摘要


protected byte[] buf


存储数据的缓冲区。


protected int count


缓冲区中的有效字节数。


*/




public static void main(String[] args) throws Exception ...{


// TODO Auto-generated method stub


ByteArrayOutputStream f=new ByteArrayOutputStream();


String s="This should end up in the array 汉字";


byte buf[] = s.getBytes();


f.write(buf);




/** *//**


* write




public void write(byte[] b,


int off,


int len)




将指定字节数组中从偏移量 off 开始的 len 个字节写入此字节数组输出流。






*/


System.out.println("Buffer as a string");


System.out.println(f.toString());




/** *//**


toString




public String toString()




将缓冲区的内容转换为字符串,根据平台的默认字符编码将字节转换成字符。


*/


System.out.println("Into array");


byte b[]=f.toByteArray();




/** *//**


* toByteArray




public byte[] toByteArray()




创建一个新分配的字节数组。其大小是此输出流的当前大小,并且缓冲区的有效内容已复制到该数组中。


*/




for(int i=0;i<b.length;i++)




...{


System.out.print((char)b[i]);


}


System.out.println(" To an OutputStream()");


OutputStream f2 = new FileOutputStream("fiel");


f.writeTo(f2);




/** *//**


* writeTo




public void writeTo(OutputStream out)


throws IOException




将此字节数组输出流的全部内容写入到指定的输出流参数中,这与使用 out.write(buf, 0, count) 调用该输出流的 write 方法效果一样。






*/


f2.close();


System.out.println("Doing a reset");


f.reset();






/** *//**


* reset




public void reset()




将此字节数组输出流的 count 字段重置为零,从而丢弃输出流中目前已累积的所有输出。通过重新使用已分配的缓冲区空间,可以再次使用该输出流。


*/


for(int i=0;i<10;i++)




...{


f.write('X');


}


System.out.println(f.toString());






}




}




import java.io.*;






public class ByteArrayInputStreamReset ...{






/** *//**


* @param args


*/




public static void main(String[] args) throws IOException...{


// TODO Auto-generated method stub


String tmp="hello";


byte b[]=tmp.getBytes();


ByteArrayInputStream in = new ByteArrayInputStream(b);


for(int i=0;i<2;i++)




...{




int c;


while((c=in.read())!=-1)




...{


if(i==0)




...{


System.out.print((char)c);


}


else




...{


System.out.print(Character.toUpperCase((char)c));


}


}




in.reset();//reset()方法两次读取同样的输入的方法:先从流中读取每个字符,并以小写字母形式打印,然后重轩设置流并比头读起,并在打印之前先将小写转换成大写字母。






}


}


}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐