Java基础—输入输出流

流的概念

在Java中,流是从源到目的地的字节的有序序列。Java中有两种基本的流——输入流(InputStream)和输出流(OutputStream)。

根据流相对于程序的另一个端点的不同,分为节点流和过滤流。

  1. 节点流:以特定源如磁盘文件、内存某区域或者线程之间的管道为端点的构造输入输出流,是一种基本的流。
  2. 过滤流:以其他已经存在的流为端点构造的输入输出流。

根据流中的数据单位分为字节流和字符流。

  1. 字节流:流中的数据是以8位字节为单位进行读写,以InputStream和OutputStream为基础类。
  2. 字符流:流中的数据是以16为字符为单位进行读写,以Reader和Writer为基础类。

Java.IO层次体系结构

Java.io是大多数面向数据流的输入/输出类的主要软件包。此外,Java也对块传输提供支持,在核心库 java.nio中采用的便是块IO。

流IO的好处是简单易用,缺点是效率较低。块IO效率很高,但编程比较复杂。

在整个Java.io包中最重要的就是5个类和一个接口。5个类指的是File、OutputStream、InputStream、Writer、Reader;一个接口指的是Serializable。掌握了这些IO的核心操作那么对于Java中的IO体系也就有了一个初步的认识了。

Java I/O主要包括如下几个层次,包含三个部分:

  1. 流式部分――IO的主体部分;
  2. 非流式部分――主要包含一些辅助流式部分的类,如:File类、RandomAccessFile类和FileDescriptor等类;
  3. 其他类――文件读取部分的与安全相关的类,如:SerializablePermission类,以及与本地操作系统相关的文件系统的类,如:FileSystem类和Win32FileSystem类和WinNTFileSystem类。

主要的类如下:

  • File(文件特征与管理):用于文件或者目录的描述信息,例如生成新目录,修改文件名,删除文件,判断文件所在路径等。
  • InputStream(二进制格式操作):抽象类,基于字节的输入操作,是所有输入流的父类。定义了所有输入流都具有的共同特征。
  • OutputStream(二进制格式操作):抽象类,基于字节的输出操作,是所有输出流的父类。定义了所有输出流都具有的共同特征。
  • Reader(文件格式操作):抽象类,基于字符的输入操作。
  • Writer(文件格式操作):抽象类,基于字符的输出操作。
  • RandomAccessFile(随机文件操作):它的功能丰富,可以从文件的任意位置进行存取(输入输出)操作。

Java中IO流的体系结构如图:

 

Java.IO流类库

java.io包中包含了流式I/O所需要的所有类。在java.io包中有四个基本类:InputStream、OutputStream及Reader、Writer类,它们分别处理字节流和字符流:

输入/输出

字节流

字符流

输入流

Inputstream

Reader

输出流

OutputStream

Writer

JDK1.4版本开始引入了新I/O类库,它位于java.nio包中,新I/O类库利用通道和缓冲区等来提高I/O操作的效率。

在java.io包中,java.io.InputStream表示字节输入流,java.io.OutputStream表示字节输出流,处于java.io包最顶层。这两个类均为抽象类,也就是说它们不能被实例化,必须生成子类之后才能实现一定的功能。

 

字节流

InputStream抽象类 

InputStream 为字节输入流,它本身为一个抽象类,必须依靠其子类实现各种功能,此抽象类是表示字节输入流的所有类的超类。 继承自InputStream的流都是向程序中输入数据的,且数据单位为字节(8bit);

InputStream是输入字节数据用的类,所以InputStream类提供了3种重载的read方法.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( ) :我们在使用完后,必须对我们打开的流进行关闭。

主要的子类:

  • FileInputStream:把一个文件作为InputStream,实现对文件的读取操作;
  • ByteArrayInputStream:把内存中的一个缓冲区作为InputStream使用;
  • StringBufferInputStream:把一个String对象作为InputStream;
  • PipedInputStream:实现了pipe的概念,主要在线程中使用;
  • SequenceInputStream:把多个InputStream合并为一个InputStream 。

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( ) : 关闭输出流并释放与流相关的系统资源。

主要的子类:

  • ByteArrayOutputStream:把信息存入内存中的一个缓冲区中 
  • FileOutputStream:把信息存入文件中 
  • PipedOutputStream:实现了pipe的概念,主要在线程中使用 
  • SequenceOutputStream:把多个OutStream合并为一个OutStream 

流结束的判断:方法read()的返回值为-1时;readLine()的返回值为null时。

文件输入流FileInputStream类

FileInputStream可以使用read()方法一次读入一个字节,并以int类型返回,或者是使用read()方法时读入至一个byte数组,byte数组的元素有多少个,就读入多少个字节。在将整个文件读取完成或写入完毕的过程中,这么一个byte数组通常被当作缓冲区,因为这么一个byte数组通常扮演承接数据的中间角色。

作用:以文件作为数据输入源的数据流。或者说是打开文件,从文件读数据到内存的类。

使用方法(1): 

File fin=new File("d:/abc.txt"); 
FileInputStream in=new FileInputStream(fin);

使用方法(2):

FileInputStream  in=new  FileInputStream(“d:/abc.txt”);
package IO;

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

/**
 * 文件输入流:FileInputStream类
 * @author Administrator
 *
 */
public class TestFile2 {
    public static void main(String[] args) {
        try {
            FileInputStream rf = new FileInputStream("E:\test\io.txt");
            int n = 512;
            byte buffer[] = new byte[n];
            while ((rf.read(buffer, 0, n) != -1) && (n > 0)) {
                System.out.println(new String(buffer));
            }
            rf.close();
        } catch (IOException IOe) {
            System.out.println(IOe.toString());
        }

    }
}
View Code

文件输出流FileOutputStream类

作用:用来处理以文件作为数据输出目的数据流;或者说是从内存区读数据写入文件。

FileOutputStream类用来处理以文件作为数据输出目的数据流;一个表示文件名的字符串,也可以是File或FileDescriptor对象。 

创建一个文件输出流对象有四种方法: 

方式1:   

File f=new File (“d:/myjava/write.txt ");
FileOutputStream out= new FileOutputStream (f);

方式2:   

FileOutputStream out=new FileOutputStream(“d:/myjava/write.txt "); 

方式3:构造函数将FileDescriptor()对象作为其参数。     

FileDescriptor() fd=new FileDescriptor(); 
FileOutputStream f2=new FileOutputStream(fd); 

方式4:构造函数将文件名作为其第一参数,将布尔值作为第二参数。   

FileOutputStream f=new FileOutputStream("d:/abc.txt",true); 

注意:

  1. 文件中写数据时,若文件已经存在,则覆盖存在的文件;
  2. 读/写操作结束时,应调用close方法关闭流。 
package IO;

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

/**
 * 文件输出流:FileOutputStream类
 * @author Administrator
 *
 */
public class TestFile3 {
    public static void main(String args[]) throws IOException {
        try {
            System.out.println("请输入:");
            int count, n = 512;
            byte buffer[] = new byte[n];
            count = System.in.read(buffer);
            FileOutputStream wf = new FileOutputStream("e:/test/io.txt");
            wf.write(buffer, 0, count);
            wf.close(); // 当流写操作结束时,调用close方法关闭流。
            System.out.println("Save to the write.txt");
        } catch (IOException IOe) {
            System.out.println("File Write Error!");
        }
    }
}
View Code

缓冲输入输出流 BufferedInputStream/ BufferedOutputStream

  计算机访问外部设备非常耗时。访问外存的频率越高,造成CPU闲置的概率就越大。为了减少访问外存的次数,应该在一次对外设的访问中,读写更多的数据。为此,除了程序和流节点间交换数据必需的读写机制外,还应该增加缓冲机制。缓冲流就是每一个数据流分配一个缓冲区,一个缓冲区就是一个临时存储数据的内存。这样可以减少访问硬盘的次数,提高传输效率。

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

将文件读入内存:将BufferedInputStream与FileInputStream相接

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

将内存写入文件:将BufferedOutputStream与 FileOutputStream相接

FileOutputStreamout=new FileOutputStream(“file1.txt”);
BufferedOutputStream  bin=new BufferedInputStream(out);

字符流Writer/Reader

  Java中字符是采用Unicode标准,一个字符是16位,即一个字符使用两个字节来表示。为此,JAVA中引入了处理字符的流。

Reader抽象类

  用于读取字符流的抽象类。子类必须实现的方法只有read(char[], int, int) 和 close()。但是,多数子类将重写此处定义的一些方法,以提供更高的效率和/或其他功能。

主要方法:

public int read() throws IOException; //读取一个字符,返回值为读取的字符 
public int read(char cbuf[]) throws IOException; /*读取一系列字符到数组cbuf[]中,返回值为实际读取的字符的数量*/ 
public abstract int read(char cbuf[],int off,int len) throws IOException; /*读取len个字符,从数组cbuf[]的下标off处开始存放,返回值为实际读取的字符数量,该方法必须由子类实现*/ 

主要的子类:

FileReader :与FileInputStream对应,主要用来读取字符文件,使用缺省的字符编码

CharArrayReader:与ByteArrayInputStream对应  

  1. 用指定字符数组作为参数:CharArrayReader(char[]) 
  2. 将字符数组作为输入流:CharArrayReader(char[], int, int) 

StringReader : 与StringBufferInputStream对应 

InputStreamReader :从输入流读取字节,在将它们转换成字符

FilterReader: 允许过滤字符流 

BufferReader :接受Reader对象作为参数,并对其添加字符缓冲器,使用readline()方法可以读取一行。

Writer抽象类

  写入字符流的抽象类。子类必须实现的方法仅有write(char[], int, int)、flush() 和 close()。但是,多数子类将重写此处定义的一些方法,以提供更高的效率和/或其他功能。

主要方法:

public void write(int c) throws IOException;//将整型值c的低16位写入输出流 
public void write(char cbuf[]) throws IOException;//将字符数组cbuf[]写入输出流
public abstract void write(char cbuf[],int off,int len) throws IOException;//将字符数组cbuf[]中的从索引为off的位置处开始的len个字符写入输出流 
public void write(String str) throws IOException;//将字符串str中的字符写入输出流 
public void write(String str,int off,int len) throws IOException;//将字符串str 中从索引off开始处的len个字符写入输出流 
flush( ); //刷空输出流,并输出所有被缓存的字节
close(); //关闭流 public abstract void close() throws IOException

其子类如下:

FileWrite: 与FileOutputStream对应 ,将字符类型数据写入文件,使用缺省字符编码和缓冲器大小。 

CharArrayWrite:与ByteArrayOutputStream对应 ,将字符缓冲器用作输出。 

PrintWrite:生成格式化输出 

FilterWriter:用于写入过滤字符流 

PipedWriter:与PipedOutputStream对应   

StringWriter:无与之对应的以字节为导向的stream  

InputStream与Reader差别, OutputStream与Writer差别

  InputStream和OutputStream类处理的是字节流,数据流中的最小单位是字节(8个bit)

  Reader与Writer处理的是字符流(16个bit),在处理字符流时涉及了字符编码的转换问题。

  Reader类能够将输入流中采用其他编码类型的字符转换为Unicode字符,然后在内存中为其分配内存

  Writer类能够将内存中的Unicode字符转换为其他编码类型的字符,再写到输出流中。

Java中流的关闭

代码中关闭流,一般可以在finally中关闭 :

File file = new File("D:" + File.separator + "test.txt");
    InputStream in = null;
    try {
        in = new FileInputStream(file);
        // operation input stream
        // ...
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
                // !!!这里如果要关闭的流很多,那么就会写出很多冗余且相似的代码
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }

如果要关闭的流很多,那么就会写出很多冗余且相似的代码,所以,需要编写方法去统一处理关闭流。

方法1:自行编码实现

可以把这个方法放到工具类中。但是本着不要重复造轮子的想法, 应该有工具类已经实现了这个方法。

private void close(Closeable closeable) {
    if (closeable != null) {
        try {
            closeable.close();
        } catch (IOException e) {
            // ignore
        }
    }
}

方法2:使用commons-io的IOUtils

Maven坐标:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

源代码:

/**
     * Unconditionally close a <code>Closeable</code>.
     * <p>
     * Equivalent to {@link Closeable#close()}, except any exceptions will be ignored.
     * This is typically used in finally blocks.
     * <p>
     * Example code:
     * <pre>
     *   Closeable closeable = null;
     *   try {
     *       closeable = new FileReader("foo.txt");
     *       // process closeable
     *       closeable.close();
     *   } catch (Exception e) {
     *       // error handling
     *   } finally {
     *       IOUtils.closeQuietly(closeable);
     *   }
     * </pre>
     *
     * @param closeable the object to close, may be null or already closed
     * @since Commons IO 2.0
     */
    public static void closeQuietly(Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (IOException ioe) {
            // ignore
        }
    }

调用示例:

public static void main(String[] args) {
    File file = new File("D:" + File.separator + "test.txt");
    InputStream in = null;
    try {
        in = new FileInputStream(file);
        // operation input stream
        // ...
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(in);
    }
 
}

方法3:try-with-resource (JDK1.7+)

在common-io-2.6版本中,这个IOUtils.closeQuietly(arg0);方法已经被弃用了,并且没有替代方案。

@Deprecated的说明如下:As of 2.6 removed without replacement. Please use the try-with-resources statement or handle suppressed exceptions manually.给我们的建议就是使用try-with-resources语句或者手动处理压制的异常。

try-with-resource这个语法糖是JDK1.7开始引入的,具体语法如下:

/**
 * auto closeable stream为实现自动关闭的Stream
 * JDK1.7 新增了一个java.lang.AutoCloseable接口,接口内部只有close()方法。
 * JDK1.7 同时修改了java.io.Closeable接口,这个接口继承了AutoCloseable接口。
 * 所以之前那些实现Closeable接口的stream都可以实现AutoCloseable接口中的自动关闭的功能。
 */
try (auto closeable stream) {
    
} catch (Exception e) {
}

示例:

public static void main(String[] args) {
    File file = new File("D:" + File.separator + "test.txt");
    try (InputStream in = new FileInputStream(file)) {
        // operation input stream
        // ...
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // ignore
    }
}

参考:

Java输入输出流

Java输入输出流(一)——常用的输入输出流

Java关闭流的方式

 

原文地址:https://www.cnblogs.com/Jason-Xiang/p/9871532.html