认识Java I/O与文件处理

(typora直接复制过来的排版崩了大半尤其是表格)
一、类图

流处理是以字节为单位的,处理Unicode编码的字符(每个代码单元两个字节)的时候,有一个专门的类层次来处理,也就是Reader和Writer这两个抽象类及它们的子类。它们的读写都是基于双字节的Unicode代码单元。

二、File类

File类既能代表一个特定文件的名称,又能表示一个目录下的一组文件的名称。对于后者,可以用list()方法返回一个字符串数组。JAVA编程思想里说,FilePath作为这个类的名字会更好。

Constructor Description
File(File parent, String child) Creates a new File instance from a parent abstract pathname and a child pathname string.
File(String pathname) Creates a new File instance by converting the given pathname string into an abstract pathname.
File(String parent, String child) Creates a new File instance from a parent pathname string and a child pathname string.
File(URI uri) Creates a new File instance by converting the given file: URI into an abstract pathname.

mkdir方法可以生成一个同名文件夹,createNewFile可以生成一个txt文本。exists可以提前检测是否已经存在该名称的文件。然后可以用流对其进行读写。

三、流:

一个可以读取字节序列的对象被称为输入流(input stream),写入字节序列的对象称为输出流(output stream)。这些字节序列的源和目的地可以是文件,网络连接甚至是内存块,从本质上来说,处理它们的方法是相同的。

第一层类介绍:

InputStream:

public abstract class InputStream

extends Object

implements Closeable

方法:

Modifier and Type Method Description
int available() Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.
void close() Closes this input stream and releases any system resources associated with the stream.
void mark(int readlimit) Marks the current position in this input stream.
boolean markSupported() Tests if this input stream supports the mark and reset methods.
abstract int read() Reads the next byte of data from the input stream.
int read(byte[] b) Reads some number of bytes from the input stream and stores them into the buffer array b.
int read(byte[] b, int off, int len) Reads up to len bytes of data from the input stream into an array of bytes.
byte[] readAllBytes() Reads all remaining bytes from the input stream.
int readNBytes(byte[] b, int off, int len) Reads the requested number of bytes from the input stream into the given byte array.
void reset() Repositions this stream to the position at the time the mark method was last called on this input stream.
long skip(long n) Skips over and discards n bytes of data from this input stream.
long transferTo(OutputStream out) Reads all bytes from this input stream and writes the bytes to the given output stream in the order that they are read.

核心方法就是read(),返回读取的字节(一个字节8个位,所以返回的结果是0-255),如果读取到了末尾,就返回-1,另外两个方法是常见的,将读出的放在参数数组中以及,读取len个字节,从数组off下标处开始存放。在其子类FileInputSream类中,有个System.in是预定义的InputStream的子类的对象。注意,read和Iterator类似,读了一个,移动一下,下次读就是下一个了。

available方法可以检查目前可以读取的字节数,利用这个方法可以避免被阻塞。

skip方法是在输入流中跳过n个字节,返回实际跳过的字节数。

OutputStream:

public abstract class OutputStream
extends Object
implements Closeable, Flushable

方法:

Modifier and Type Method Description
void close() Closes this output stream and releases any system resources associated with this stream.
void flush() Flushes this output stream and forces any buffered output bytes to be written out.
void write(byte[] b) Writes b.length bytes from the specified byte array to this output stream.
void write(byte[] b, int off, int len) Writes len bytes from the specified byte array starting at offset off to this output stream.
abstract void write(int b) Writes the specified byte to this output stream.

核心方法就是write,把数组中的字节,写到对象中。off就是偏移量,从数组的哪里开始写,写多少(len)。

两个类都有close方法,当完成了对一个流的读取或者写入后,应该调用close方法将它关闭,释放流所占用的操作系统资源。同时关闭一个输出流,可以起到刷新(flush方法)输出流占用的缓存区的作用,也就是临时存储在缓冲区,等待形成较大的数据包后再发送的那些字符。

如果不关闭文件,最后一个字节包可能永远也不会被发送。不过在 try() 括号中打开流,是会自动关闭流对象 的,不用close。

flush方法,刷新输出流,将缓冲区的所有数据发送到目的地。

read 是读取调用它的对象的数据,可以将读取出的,放到参数数组里;write 是从参数数组里读取数据,写入调用对象里。究竟是read还是write,是基于对象而言。

注意以上这两个类对流的操作都是基于字节的,处理的是二进制对象或字节,和字符流 (Reader和Writer)是不一样的。如果想要读取具体的内容而不是字节数据,就要把读取到的字节转码。

Reader:

  • java.lang.Object
    • java.io.Reader
    • All Implemented Interfaces:
      Closeable, AutoCloseable, Readable
    • Direct Known Subclasses:
      BufferedReader, CharArrayReader, FilterReader, InputStreamReader, PipedReader, StringReader, URLReader

构造方法:

Modifier Constructor Description
protected Reader() Creates a new character-stream reader whose critical sections will synchronize on the reader itself.
protected Reader(Object lock) Creates a new character-stream reader whose critical sections will synchronize on the given object.

其他方法:

Modifier and Type Method Description
abstract void close() Closes the stream and releases any system resources associated with it.
void mark(int readAheadLimit) Marks the present position in the stream.
boolean markSupported() Tells whether this stream supports the mark() operation.
int read() Reads a single character.
int read(char[] cbuf) Reads characters into an array.
abstract int read(char[] cbuf, int off, int len) Reads characters into a portion of an array.
int read(CharBuffer target) Attempts to read characters into the specified character buffer.
boolean ready() Tells whether this stream is ready to be read.
void reset() Resets the stream.
long skip(long n) Skips characters.

从read的参数类型就可以看出,这里读取的就已经是字符了。每个字符或者汉字都是占2个字节(Unicode)。

InputStream类的read()方法只是简单的从输入流里面取出一个字节,然后返回他的值,Reader类的read()方法则是先判断出输入流使用的是何种编码方式(实际上如果我们不指定编码,则直接使用系统的默认编码作为输入流的编码,在中文Windows系统中默认为GB2312),然后用输入流的编码方式解码出一个字符(输入流的编码方式确定了也就确定了读取一个字符需要取出个字节),取出一个字符后再把这个字符用UTF-16BE编码并返回编码值,这就是read()方法返回的值。 

(来源:https://www.cnblogs.com/xxNote/p/5414193.html

Writer:

  • java.lang.Object
    • java.io.Writer
    • All Implemented Interfaces:
      Closeable, Flushable, Appendable, AutoCloseable
    • Direct Known Subclasses:
      BufferedWriter, CharArrayWriter, FilterWriter, OutputStreamWriter, PipedWriter, PrintWriter, StringWriter

构造方法:

Modifier Constructor Description
protected Writer() Creates a new character-stream writer whose critical sections will synchronize on the writer itself.
protected Writer(Object lock) Creates a new character-stream writer whose critical sections will synchronize on the given object.

其他方法:

Modifier and Type Method Description
Writer append(char c) Appends the specified character to this writer.
Writer append(CharSequence csq) Appends the specified character sequence to this writer.
Writer append(CharSequence csq, int start, int end) Appends a subsequence of the specified character sequence to this writer.
abstract void close() Closes the stream, flushing it first.
abstract void flush() Flushes the stream.
void write(char[] cbuf) Writes an array of characters.
abstract void write(char[] cbuf, int off, int len) Writes a portion of an array of characters.
void write(int c) Writes a single character.
void write(String str) Writes a string.
void write(String str, int off, int len) Writes a portion of a string.

部分子类:

FileInputStream和FileOutputStream

这两个类能够把输入和输出流与磁盘文件关联起来。

FileInputStream fin = new FileInputStream("C:\a.txt");通过在构造其中给出文件路径与文件名即可。由于反斜线在Java字符串中作转义符,所以用双斜杠作为路径分隔符。Windows中也可以用正斜线 / 来代替(不推荐)。当然也可以用一个File对象作构造的参数。

注意,java.io中的类都是将相对路径名解释为用户的当前工作目录,可以用这个更方便直接打开部分文件。

  • java.lang.Object
    • java.io.InputStream
      • java.io.FileInputStream
    • All Implemented Interfaces:
      Closeable, AutoCloseable

构造方法:

Constructor Description
FileInputStream(File file) Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system.
FileInputStream(FileDescriptor fdObj) Creates a FileInputStream by using the file descriptor fdObj, which represents an existing connection to an actual file in the file system.
FileInputStream(String name) Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system.

String参数传入的就是上述举例(路径+)文件名,File参数也类似,都是建立一个与相应文件连接的“流”。

其他方法:

Modifier and Type Method Description
int available() Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.
void close() Closes this file input stream and releases any system resources associated with the stream.
protected void finalize() Deprecated. The finalize method has been deprecated. Subclasses that override finalize in order to perform cleanup should be modified to use alternative cleanup mechanisms and to remove the overriding finalize method. When overriding the finalize method, its implementation must explicitly ensure that super.finalize() is invoked as described in Object.finalize(). See the specification for Object.finalize() for further information about migration options.
FileChannel getChannel() Returns the unique FileChannel object associated with this file input stream.
FileDescriptor getFD() Returns the FileDescriptor object that represents the connection to the actual file in the file system being used by this FileInputStream.
int read() Reads a byte of data from this input stream.
int read(byte[] b) Reads up to b.length bytes of data from this input stream into an array of bytes.
int read(byte[] b, int off, int len) Reads up to len bytes of data from this input stream into an array of bytes.
long skip(long n) Skips over and discards n bytes of data from the input stream.

  • java.lang.Object
    • java.io.OutputStream
      • java.io.FileOutputStream
    • All Implemented Interfaces:
      Closeable, Flushable, AutoCloseable

构造方法:

Constructor Description
FileOutputStream(File file) Creates a file output stream to write to the file represented by the specified File object.
FileOutputStream(FileDescriptor fdObj) Creates a file output stream to write to the specified file descriptor, which represents an existing connection to an actual file in the file system.
FileOutputStream(File file, boolean append) Creates a file output stream to write to the file represented by the specified File object.
FileOutputStream(String name) Creates a file output stream to write to the file with the specified name.
FileOutputStream(String name, boolean append) Creates a file output stream to write to the file with the specified name.

append参数是用来判断是否将字节写入文件的末尾(true插入末尾)。

其他方法:

Modifier and Type Method Description
void close() Closes this file output stream and releases any system resources associated with this stream.
protected void finalize() Deprecated. The finalize method has been deprecated. Subclasses that override finalize in order to perform cleanup should be modified to use alternative cleanup mechanisms and to remove the overriding finalize method. When overriding the finalize method, its implementation must explicitly ensure that super.finalize() is invoked as described in Object.finalize(). See the specification for Object.finalize() for further information about migration options.
FileChannel getChannel() Returns the unique FileChannel object associated with this file output stream.
FileDescriptor getFD() Returns the file descriptor associated with this stream.
void write(byte[] b) Writes b.length bytes from the specified byte array to this file output stream.
void write(byte[] b, int off, int len) Writes len bytes from the specified byte array starting at offset off to this file output stream.
void write(int b) Writes the specified byte to this file output stream.

相应的字符流的Reader和Writer子类:FileReader和FileWriter:

  • java.lang.Object
    • java.io.Reader
      • java.io.InputStreamReader//字节到字符的桥梁
        • java.io.FileReader
    • All Implemented Interfaces:
      Closeable, AutoCloseable, Readable

构造方法:

Constructor Description
FileReader(File file) Creates a new FileReader, given the File to read from.
FileReader(FileDescriptor fd) Creates a new FileReader, given the FileDescriptor to read from.
FileReader(String fileName) Creates a new FileReader, given the name of the file to read from.

  • java.lang.Object
    • java.io.Writer
      • java.io.OutputStreamWriter
        • java.io.FileWriter
    • All Implemented Interfaces:
      Closeable, Flushable, Appendable, AutoCloseable

构造方法:

Constructor Description
FileWriter(File file) Constructs a FileWriter object given a File object.
FileWriter(FileDescriptor fd) Constructs a FileWriter object associated with a file descriptor.
FileWriter(File file, boolean append) Constructs a FileWriter object given a File object.
FileWriter(String fileName) Constructs a FileWriter object given a file name.
FileWriter(String fileName, boolean append) Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.

其它方法参照以上。

PipedOutputStream和PipedInputStream:线程间通信。

ByteArrayInputStream和ByteArrayOutputStream:在内存中创建一个字节数组缓冲区 用IO流的方式来完成对字节数组的读写。

FilterInputStream和FilteroutputStream及子类:

这两个类的作用是封装其它的输入输出流(以其他流为参数),并为它们提供额外的功能(没错就是典型的装饰设计模式)

  • java.lang.Object
    • java.io.InputStream
      • java.io.FilterInputStream
    • All Implemented Interfaces:
      Closeable, AutoCloseable

构造方法:

Modifier Constructor Description
protected FilterInputStream(InputStream in) Creates a FilterInputStream by assigning the argument in to the field this.in so as to remember it for later use.

其他方法:

就是InputStream的实现。

  • java.lang.Object
    • java.io.OutputStream
      • java.io.FilterOutputStream
    • All Implemented Interfaces:
      Closeable, Flushable, AutoCloseable

构造方法:

Constructor Description
FilterOutputStream(OutputStream out) Creates an output stream filter built on top of the specified underlying output stream.

其他方法也是实现了OutputStream。

这两个类的关键在于它们的子类,包括:

BufferedInputStream, CheckedInputStream, CipherInputStream, DataInputStream, DeflaterInputStream, DigestInputStream, InflaterInputStream, LineNumberInputStream, ProgressMonitorInputStream, PushbackInputStream 等

BufferedOutputStream, CheckedOutputStream, CipherOutputStream, DeflaterOutputStream, DigestOutputStream等。

部分子类作用:

BufferedInputStream(InputStream in) //新建一个默认大小的缓冲流,缓冲的输入流从一个流中读取字符,而不会每次都引起对设备的访问。当缓冲区为空时,一个新的数据块将会被读入缓冲区。

BufferedInputStream(InputStream in, int n)//n是缓冲区的大小,新建一个缓冲流。



BufferedOutputStream(OutputStream out)//新建一个默认缓冲大小的缓冲流。缓冲输出流手机写入的字符以避免每次都引起对设备的访问。当缓存区满或流被刷新时,数据被写入设备。

BufferedOutputStream(OutputStream out,int n)//根据用户自定义的缓冲区大小,新建一个缓冲流



PushbackInputStream(InputStream in)//构造一个预查一个字节的流。

pushbackInputStream(InputStream in, int size)//使用指定大小的pushback缓冲区构造一个流。 



CipherInputStream、CipherOutputStream,加密流

DataInputStream、DataOutputStream,数据输入输出流,有readDouble()这类方法。

……

BufferedReader和BufferedWriter及子类:带有默认缓冲的字符输出输入流,为其他字符输入输出流添加缓冲功能。

  • java.lang.Object
    • java.io.Reader
      • java.io.BufferedReader
    • All Implemented Interfaces:
      Closeable, AutoCloseable, Readable
    Constructor Description
    BufferedReader(Reader in) Creates a buffering character-input stream that uses a default-sized input buffer.
    BufferedReader(Reader in, int sz) Creates a buffering character-input stream that uses an input buffer of the specified size.

构造函数指定一个Reader参数,通过分次将Reader流缓冲到内存的方式,提高读取的效率。

Modifier and Type Method Description
void close() Closes the stream and releases any system resources associated with it.
Stream

  • java.lang.Object
    • java.io.Writer
      • java.io.BufferedWriter
    • All Implemented Interfaces:
      Closeable, Flushable, Appendable, AutoCloseable

    Constructor Description
    BufferedWriter(Writer out) Creates a buffered character-output stream that uses a default-sized output buffer.
    BufferedWriter(Writer out, int sz) Creates a new buffered character-output stream that uses an output buffer of the given size.

    Modifier and Type Method Description
    void close() Closes the stream, flushing it first.
    void flush() Flushes the stream.
    void newLine() Writes a line separator.
    void write(char[] cbuf, int off, int len) Writes a portion of an array of characters.
    void write(int c) Writes a single character.
    void write(String s, int off, int len) Writes a portion of a String.

newLine是写一个行分隔符,也就是换行。

RandomAccessFile:随机读取文件流

能够在磁盘文件的任何位置查找或者写入数据,同时实现了DataInput和DataOutput接口。

猜你喜欢

转载自www.cnblogs.com/mutojack/p/9341597.html