ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

字节输入流读取字节数据和字节输入流一次读取多个字节

2022-07-14 10:04:36  阅读:141  来源: 互联网

标签:字节 read int println FileInputStream 输入 读取


读取数据的原理(硬盘-->内存)
java程序-->JVM-->OS-->OS读取数据的方法-->读取文件
字节输入流的使用步骤:
1.创建FileInputStream对象,构造方法中绑定要读取的数据源
2.使用FileInputStream对象中的方法read,读取文件
3.释放资源

package com.yang.Test.IOStudy;

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

public class InStudy01 {
    public static void main(String[] args) throws IOException {
        FileInputStream in = new FileInputStream("Document\\1.txt");
        int read = in.read();
        System.out.println(read);//97 a

        read = in.read();
        System.out.println(read);//98 b

        read = in.read();
        System.out.println(read);//99 c
        //int read()读取文件中的一个字节并且返回,读取到文件末尾返回-1
        read = in.read();
        System.out.println(read);//-1

        /**
         * 发现以上读取文件是一个重复的过程,所以可以使用循环优化
         * 不知道文件中有多少字节,使用while循环
         * while循环结束条件,读取到-1的使用结束
         */
        int len = 0;

        while ((len = in.read()) != -1) {
            System.out.println((char) len);
        }


        in.close();
    }
}

字节输入流一次读取多个字节

package com.yang.Test.IOStudy;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;

/**
 * 字节输入流一次读取多个字节的方法:
 * int read(byte b)从输入流中读取一定数量的字节,并将其存储在缓冲区数组b中。
 * 明确两件事情:
 * 1.方法的参数byte[]的作用?
 * 2.方法的返回值int是什么?
 *
 * String类的构造方法
 * String(byte[] bytes):把字节数组转换为字符串
 * String(byte[] bytes,int offset,int length)把字节数组的一部分转换为字符串 offset:数组的开始索引,length:转换的字节个数
 */
public class InStudy01 {
    public static void main(String[] args) throws IOException {
        //创建FileInputStream对象,构造方法中绑定要读取的数据源
        FileInputStream in = new FileInputStream("Document\\bbb.txt");
        //使用FileInputStream对象中的read读取文件
        //int read(byte[] b)从输入流中读取一定数量的字节,并将其存储在缓冲区数组b中

        byte[] bytes = new byte[2];
        int read = in.read(bytes);
        System.out.println(read);//2
        System.out.println(Arrays.toString(bytes));//[112, 97]
        System.out.println(new String(bytes));//pa

        in.close();
    }
}

标签:字节,read,int,println,FileInputStream,输入,读取
来源: https://www.cnblogs.com/ailhy/p/16476516.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有