流与文件

(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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值