Java输入、输出流

一、文件字节输入流

1. 构造方法

FileInputStream(String name);
FileInputStream(File file);

参数name和file指定的文件称为输入流的源
FileInputStream输入流打开一个到达文件的通道,当创建输入流时,可能会抛出IOException(IO异常)。

//使用构造函数
//FileInputStream(String name);
try {
    FileInputStream input = new FileInputStream("f:/1.txt");
}catch (IOException e){
    e.printStackTrace();
}
//FileInputStream(File file);
File file = new File("f:/1.txt");
try {
    FileInputStream input = new FileInputStream(file );
}catch (IOException e){
    e.printStackTrace();
}

2.使用输入流读取字节

输入流的目的是提供读取源中数据的通道,程序可以通过这个通道读取源中的数据。
文件字节流可以调用从父类继承的read方法顺序读取文件,只要不关闭流,每次调用read方法就顺序地读取文件中的其余内容,直到文件的末尾或文件字节输入流被关闭。

  1. int read() 从源中读取单个字节的数据,该方法返回字节值(0~255之间的一个整数),如果未读出字节就返回-1.
  2. int read(byte b[ ]) 从源中试图读取b.length个字节到字节数组b中,返回实际读取的字节数目。如果到达文件的末尾,则返回-1。
  3. int read(byte b[ ],int off,int len) 从源中试图读取len个字节到字节数组b中,并返回实际读取的字节数目。如果到达文件的末尾,则返回-1,参数off指定从字节数组的某个位置开始存放读取的数据。

3.关闭流

输入流都提供了关闭方法close(),虽然程序结束时会自动关闭所有打开的流,显示地关闭仍是一个良好的习惯。

4.测试

public class FileRead {
    public void write(String file) throws Exception{
        FileInputStream input = new FileInputStream(file);
        byte[] buf = new byte[256];
        int length = 0;
        while((length=input.read(buf))!=-1){
            String s = new String(buf,0,length);
            System.out.println(s);
        }
        input.close();
    }
}

二、文件字节输出流

1.构造方法

FileOutputStream(String name);
FileOutputStream(File file);

参数name和file指定的文件称为输出流的目的地。
如果输出流指向的文件不存在,Java就会创建该文件,如果指向的文件是已存在的文件,输出流将刷新该文件(使得文件长度为0)。

FileOutputStream(String name,boolean append);
FileOutputStream(File file,boolean append);

如果参数append取值true,输出流不会刷新所指向的文件,将从文件的末尾开始向文件写入数据。

2.使用输出流写字节

文件字节流可以调用从父类继承的write方法顺序地写文件。FileOutputStream流顺序地向文件写入内容,即只要不关闭流,每次调用write方法就顺序地向文件写入内容,直到流被关闭。

  1. void write(int n) 向目的地写入单个字节。
  2. void write(byte b[ ]) 向目的地写入一个字节数组。
  3. void write(byte b[ ],int off,int len) 给定字节数组中起始于偏移量off处取len个字节写到目的地。
  4. void close() 关闭输出流。

3.关闭流

需要注意的是,在操作系统把程序写到输出流的那些字节保存到磁盘上之前,有时被存放在内存缓冲区中,通过调用close()方法,可以保证操作系统把流缓冲区的内容写到它的目的地,即关闭输出流可以把该流所用的缓冲区的内容洗掉。

4.测试

public class FileWrite {
    public void write() throws Exception{
        byte[] a = "Haley, ".getBytes();
        byte[] b = "happy new year!".getBytes();
        FileOutputStream outputStream = new FileOutputStream("f:/1.txt");
        outputStream.write(a);
        outputStream = new FileOutputStream("f:/1.txt",true);
        outputStream.write(b);
        outputStream.close();
    }
}

三、文件字符输入、输出流

1.构造方法

FileReader(String filename);
FileReader(File filename);
FileWriter(String filename);
FileWriter(String filename);
FileWriter(String filename,boolean append);
FileWriter(File filename,boolean append);

字符输入流和输出流的read和write方法使用字符数组读写数据,即以字符为基本单位处理数据。

2.测试

public class FileRead {
    public void write() throws Exception{
        FileReader reader = new FileReader("f:/1.txt");
        FileWriter writer = new FileWriter("f:/2.txt");
        char[] c = new char[256];
        int length = 0;
        while((length=reader.read(c))!=-1){
            writer.write(c,0,length);
        }
        writer.flush();
        writer.close();
        reader.close();
    }
}

四、缓冲流

BufferedReader 和 BufferedWriter 类创建的对象称为缓冲输入、输出流,二者增强了读写文件的能力。

1.构造方法

BufferedReader(Reader in);
BufferedWriter(Writer out);

关闭输出流时要首先关闭缓冲输出流,然后关闭缓冲输出流指向的流,即先关闭上层流再关闭底层流。在编写代码时只需要关闭上层流,那么上层流的底层流将自动关闭。

2.测试

public class FileRead {
    public void write() throws Exception{
        FileReader reader = new FileReader("f:/1.txt");
        FileWriter writer = new FileWriter("f:/2.txt");
        BufferedReader bufferedReader = new BufferedReader(reader);
        BufferedWriter bufferedWriter = new BufferedWriter(writer);
        String string = null;
        while((string = bufferedReader.readLine())!=null){
            bufferedWriter.write(string);
            bufferedWriter.newLine();
        }
        bufferedWriter.flush();
        bufferedWriter.close();
        bufferedReader.close();
        writer.close();
        reader.close();
    }
}

五、随机流

RandomAccessFile类创建的流称作随机流,随机流的指向既可以作为流的源,也可以作为流的目的地。

1.构造方法

RandomAccessFile(String name,String mode);
RandomAccessFile(File file,String mode);

参数mode取r(只读)或rw(可读写)

RandomAccessFile流指向文件时,不刷新文件。

RandomAccessFile类中有一个方法seek(long a)用来定位RandomAccessFile流的读写位置,其中参数a确定读写位置距离文件开头的字节个数。另外流还可以调用getFilePointer()方法获取流的当前读写位置。

2.测试

public class FileRead {
    public void write() throws Exception{
        int[] data = {1,2,3,4,5,6,7,8,9};
        RandomAccessFile inAndOut = new RandomAccessFile("f:/2.txt","rw");
        for(int i=0;i<data.length;i++){
            inAndOut.writeInt(data[i]);
        }
        for(int i=data.length-1;i>=0;i--){
            long position = 4*i;
            inAndOut.seek(position);
            System.out.println(inAndOut.readInt());
        }
    }
}

六、数组流

1.字节数组流

//源是参数buf指定的数组的全部字节单元
ByteArrayInputStream(byte[] buf);
//源是buf指定的数组从offset处按顺序
ByteArrayInputStream(byte[] buf,int offset,int length);

ByteArrayOutputStream();
ByteArrayOutputStream(int size);

2.字符数组流

CharArrayReader
CharArrayWriter

七、数据流

1.构造方法

DataInputStream(InputStream in);
DataOutputStream(OutputStream out);

它们允许程序按着机器无关的风格读取Java原始数据。也就是说,当读取一个数值时,不必关心这个数值应当是多少个字节。

2.测试

public class Test {
    public static void main(String[] args){
        try {
            FileOutputStream outputStream = new FileOutputStream("f:/1.txt");
            DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
            dataOutputStream.writeInt(12);
            dataOutputStream.writeInt(13);
            dataOutputStream.writeInt(14);
            FileInputStream inputStream = new FileInputStream("f:/1.txt");
            DataInputStream dataInputStream = new DataInputStream(inputStream);
            System.out.println(dataInputStream.readInt());
            System.out.println(dataInputStream.readInt());
            System.out.println(dataInputStream.readInt());
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

在这里插入图片描述

八、对象流

1.构造方法

ObjectInputStream(InputStream in);
ObjectOutPutStream(OutputStream out);

当使用对象流写入或读入对象时,要保证对象是序列化的。这是为了保证能把对象写入到文件,并能再把对象正确读回到程序中。
一个类如果实现了Serializable接口,那么这个类创建的对象就是序列化的对象。

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值