IO---字节流

字节输出流
***

此抽象类是表示输出字节流的所有类的超类。输出流接受输出字节并将这些字节发送到某个接收器。
    public abstract class OutputStream implements Closeable, Flushable

Flushable接口只定义了一个flush方法,调用时,会将缓存中的数据写入到流中。

  • 方法

    void close()                            //关闭此输出流并释放与此流有关的所有系统资源。 
    void flush()                            //刷新此输出流并强制写出所有缓冲的输出字节。 
    void write(byte[] b)                    //将 b.length 个字节从指定的 byte 数组写入此输出流。 
    void write(byte[] b, int off, int len)  //将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此输出流。 
    abstract  void write(int b)             //将指定的字节写入此输出流。 

FileOutputStream(文件字节输出流)

public class FileOutputStreamextends OutputStream
构造方法里FileOutputStream(String name, boolean append) append默认是false,表示写入数据追加到已有数据后面,false表示覆盖原数据。

eg

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class FileTest {
    
    public static void main(String[] args) throws IOException {
        OutputStream os = new FileOutputStream("d:/blog/test.txt");
        //OutputStream os = new FileOutputStream("d:/blog/test.txt",true); true追加,false覆盖
        os.write("Test OutputStream".getBytes());
        os.close();
    }
}

字节输入流
***

此抽象类是表示字节输入流的所有类的超类。 
    public abstract class InputStream implements Closeable
  • 方法

    int available()                             //返回此输入流下一个方法调用可以不受阻塞地从此输入流读取(或跳过)的估计字节数。 
    void close()                                //关闭此输入流并释放与该流关联的所有系统资源。 
    void mark(int readlimit)                    //在此输入流中标记当前的位置。 
    boolean markSupported()                     //测试此输入流是否支持 mark 和 reset 方法。 
    abstract  int read()                        //从输入流中读取数据的下一个字节。 
    int read(byte[] b)                          //从输入流中读取一定数量的字节,并将其存储在缓冲区数组 b 中。 
    int read(byte[] b, int off, int len)        //将输入流中最多 len 个数据字节读入 byte 数组。 
    void reset()                                //将此流重新定位到最后一次对此输入流调用 mark 方法时的位置。 
    long skip(long n)                           //跳过和丢弃此输入流中数据的 n 个字节。 

FileOutputStream(文件字节输出流)

public class FileOutputStreamextends OutputStream

eg

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileTest {
    public static void main(String[] args) throws IOException {
        InputStream is = new FileInputStream("d:/blog/test.txt");
        int len = -1;
        byte[] buffer  = new byte[10];
        while((len=is.read(buffer))!=-1){
             System.out.print(new String(buffer,0,len));
        }
        is.close();
    }
}

猜你喜欢

转载自www.cnblogs.com/Ch1nYK/p/8921508.html