InputStream和OutputStream

来源:互联网 发布:软件空免费下载 编辑:程序博客网 时间:2024/05/16 04:18

在java.io包中提供了60多个类(流)。

(1)从功能上分为两大类:输入流和输出流。

(2)从流结构上可分为字节流和字符流。 

字节流类(Byte Streams)字节流类用于向字节流读写8位二进制的字节。一般地,字节流类主要用于读写诸如图像或声音等的二进制数据。

字符流类(Character Streams)字符流类用于向字符流读写16位二进制字符。

(3)节点流:从特定的地方读写的流类,例如:磁盘一块内存区域。(即与目标直接打交道的流

常使用的节点流有:

FileInputStream、FileOutputStream

ByteArrayInputStream、ByteArrayOutputStream

过滤流:使用节点流作为输入或输出,过滤流是使用一个已经存在的输入流或输出流链接创建的。(它不能与目标直接打交道

1.FileInputStream的使用

package com.sailang.java;import java.io.FileInputStream;import java.io.InputStream;public class InputStreamTest{public static void main(String[] args) throws Exception{//打开流InputStream is = new FileInputStream("D:/lizhongyi.txt");//读取流byte[] buffer = new byte[200];int length = 0;while(-1 != (length = is.read(buffer, 0, 200))){String s = new String(buffer, 0, length);System.out.println(s);}//关闭流is.close();}}

结果:

32
lizhongyi
gengtao
xunliceng
a

问题:

(1)读了几次?

(2)怎么读取换行符的?

 

2.FileOutputStream的使用

package com.sailang.java;import java.io.FileOutputStream;import java.io.OutputStream;public class OutputStreamTest1{public static void main(String[] args) throws Exception{//打开要写入的流文件OutputStream os = new FileOutputStream("D:/out.txt");String str = "Hello World";byte[] buffer = str.getBytes();//将buffer写入到输出流中os.write(buffer);    //关闭流os.close();}}

3、过滤流BufferedOutputStream类的使用

package com.sailang.java;import java.io.BufferedOutputStream;import java.io.FileOutputStream;import java.io.OutputStream;public class BufferedOutputStreamTest{public static void main(String[] args) throws Exception{//打开需要写入的文件流OutputStream os = new FileOutputStream("D:/lizhongyi.txt");//过滤流封装BufferedOutputStream bos = new BufferedOutputStream(os);//写入数据String str = "lizhongyi";bos.write(str.getBytes());//关闭文件流bos.close();}}

4、ByteArrayInputStream

ByteArrayInputStream把字节数组当作源,将内存的缓存区当作InputStream使用。

package com.sailang.java;import java.io.ByteArrayInputStream;import java.io.IOException;public class ByteArrayInputStreamTest{public static void main(String[] args) throws IOException{//打开输入流//数据源String str = "lizhogyi";byte[] b = str.getBytes();//将字节数组作为源的输入流ByteArrayInputStream f = new ByteArrayInputStream(b);//读入数据,一个字节一个字节的读,每个返回的字节占用int的最后8位,读到末尾返回-1int a;while(-1 != (a = f.read())){System.out.println((char)a);}//关闭流//Closing a ByteArrayInputStream has no effect. //The methods in this class can be called after the stream has been closed without generating an IOException.//f.close();}}

5、ByteArrayoutputStream

package com.sailang.java;import java.io.ByteArrayOutputStream;import java.io.FileOutputStream;import java.io.OutputStream;public class ByteArrayOutputStreamTest{public static void main(String[] args) throws Exception{ByteArrayOutputStream baos = new ByteArrayOutputStream();String str = "lizhongyiddddd";byte[] buffer = str.getBytes();baos.write(buffer);OutputStream os = new FileOutputStream("D:/out.txt");baos.writeTo(os);baos.close();os.close();}}