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

Java输入输出流

2015-09-01 15:27 381 查看
InputStream(读数据) OutputStream(写数据)都是字节流,以二进制格式操作,除此之外还有Reader(读),Writer(写)字符流。这里的读和写都是相对程序而言,外部数据进入程序,通过输入流完成。程序将数据给外部设备,通过输出流完成。 一个字符占两个字节。

1.InputStream

Inputstream类中的常用方法:

  (1) public abstract int read( ):读取一个byte的数据,返回值是高位补0的int类型值。若返回值=-1说明没有读取到任何字节读取工作结束。

  (2) public int read(byte b[ ]):读取b.length个字节的数据放到b数组中。返回值是读取的字节数。该方法实际上是调用下一个方法实现的

  (3) public int read(byte b[ ], int off, int len):从输入流中最多读取len个字节的数据,存放到偏移量为off的b数组中。

  (4) public int available( ):返回输入流中可以读取的字节数。注意:若输入阻塞,当前线程将被挂起,如果InputStream对象调用这个方法的话,它只会返回0,这个方法必须由继承InputStream类的子类对象调用才有用,

  (5) public long skip(long n):忽略输入流中的n个字节,返回值是实际忽略的字节数, 跳过一些字节来读取

  (6) public int close( ) :我们在使用完后,必须对我们打开的流进行关闭.

  

File f=new File("1.txt");
InputStream in=new FileInputStream(f);//获得一个输入流,用于向程序中输入
byte[] b=new byte[1024];//创建一个大小合适的字节数组
int len=0;
int temp=0;//
while((len=in.read(b))!=-1){//读取b.length个字节
temp+=len;//总共读取了多少个字节
}


2.OutputStream

OutputStream提供了3个write方法来做数据的输出,这个和 InputStream是相对应的。

  1. public void write(byte b[ ]):将参数b中的字节写到输出流。

  2. public void write(byte b[ ], int off, int len) :将参数b的从偏移量off开始的len个字节写到输出流。

  3. public abstract void write(int b) :先将int转换为byte类型,把低字节写入到输出流中。

  4. public void flush( ) : 将数据缓冲区中数据全部输出,并清空缓冲区。

  5. public void close( ) : 关闭输出流并释放与流相关的系统资源。

3.缓冲输入输出流 BufferedInputStream/ BufferedOutputStream

BufferedInputStream:当向缓冲流写入数据时候,数据先写到缓冲区,待缓冲区写满后,系统一次性将数据发送给输出设备。

BufferedOutputStream :当从向缓冲流读取数据时候,系统先从缓冲区读出数据,待缓冲区为空时,系统再从输入设备读取数据到缓冲区。

1)将文件读入内存:

将BufferedInputStream与FileInputStream相接

FileInputStream in=new FileInputStream( “file1.txt ” );

BufferedInputStream bin=new BufferedInputStream( in);

2)将内存写入文件:

将BufferedOutputStream与 FileOutputStream相接

FileOutputStreamout=new FileOutputStream(“file1.txt”);

BufferedOutputStream bin=new BufferedInputStream(out);

3)键盘输入流读到内存

将BufferedReader与标准的数据流相接

InputStreamReader sin=new InputStreamReader (System.in) ;

BufferedReader bin=new BufferedReader(sin);

import java.io.*;  

    public class ReadWriteToFile {  
        public static void main(String args[]) throws IOException {  
            InputStreamReader sin = new InputStreamReader(System.in);  
            BufferedReader bin = new BufferedReader(sin);  
            FileWriter out = new FileWriter("myfile.txt");  
            BufferedWriter bout = new BufferedWriter(out);  
            String s;  
            while ((s = bin.readLine()).length() > 0) {  
                bout.write(s, 0, s.length());  
            }  

        }  
    }


程序说明:

从键盘读入字符,并写入到文件中BufferedReader类的方法:String readLine()

作用:读一行字符串,以回车符为结束。

BufferedWriter类的方法:bout.write(String s,offset,len)

作用:从缓冲区将字符串s从offset开始,len长度的字符串写到某处。

深入了解请访问:

http://blog.csdn.net/hguisu/article/details/7418161
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: