流
(1):输入流和输出流的定义:
可以从文本文件中读入一个字节序列的对象称作输入流,而可以向其中写入一个字节序列的对象叫做输出流。 在Java中,文件的输入和输出是通过流(Stream)来实现的。一个流,必有源端和目的端,它们可以是计算机内存的某些区域,也可以是磁盘文件,甚至可以是 Internet 上的某个 URL。
(2):字节流和字符流
流按照处理数据的单位,可以分为字节流和字符流。字节流的处理单位是字节,通常用来处理二进制文件,例如音乐、图片文件等。而字符流的处理单位是字符,因为Java采用Unicode编码,Java字符流处理的即为Unicode字符,所以在操作汉字、国际化等方面,字符流具有优势。
字节流
1: 所有的字节流都继承自InputStream和OutputStream这两个抽象类。
2:读入字节
(1):InputStream类具有若干个非抽象的方法,他们可以读入一个字节数组,或者跳过大量的字节。这些方法都要调用抽象的read()方法,因此,各个子列都只需要覆盖这一个方法。
(2):FileInputStream类继承自InputStream类,该子类中通过覆盖父类read()方法来实现读入字节的功能。其源码如下所示
package java.io;
import java.nio.channels.FileChannel;
import sun.nio.ch.FileChannelImpl;
public class FileInputStream extends InputStream
{
private final FileDescriptor fd;
private final String path;
private volatile FileChannel channel;
private final Object closeLock = new Object();
/**
* Reads a byte of data from this input stream. This method blocks
* if no input is yet available.
*
* @return the next byte of data, or {@code -1} if the end of the
* file is reached.
* @throws IOException if an I/O error occurs.
*/
public int read() throws IOException {
return read0();
}
private native int read0() throws IOException;
/**
* Reads a subarray as a sequence of bytes.
* @param b the data to be written
* @param off the start offset in the data
* @param len the number of bytes that are written
* @throws IOException If an I/O error has occurred.
*/
private native int readBytes(byte b[], int off, int len) throws IOException;
/**
* Reads up to {@code b.length} bytes of data from this input
* stream into an array of bytes. This method blocks until some input
* is available.
*
* @param b the buffer into which the data is read.
* @return the total number of bytes read into the buffer, or
* {@code -1} if there is no more data because the end of
* the file has been reached.
* @throws IOException if an I/O error occurs.
*/
public int read(byte b