(Byte stream and character stream) InputStream byte input stream

Corresponding to the OutputStream class is the Zijie input stream, and InputStream mainly implements byte array reading.

public abstract class InputStream extends Object implements Closeable

The following core methods are defined in OutputStream:

  • Read a single byte of data: public abstract int read() throws IOException (returns the specific byte data, if it has been read to the end, return -1)
  • Read a set of byte data: public int read​(byte[] b) throws IOException is the most commonly used (read a set of byte arrays, return the number of reads, if no data has been read to the end, return -1)
  • Read part of a set of byte data (off-len): public int read​(byte[] b, int off, int len) throws IOException

The IputStream class belongs to an abstract class. At this time, you should rely on its subclass to instantiate the object. If you want to read from the file, you must use the FileInputStream subclass. For the subclass, you only care about the instantiation of the parent class object. The construction method: public FileInputStream​(File file) throws FileNotFoundException

Example: Read data

package 字节流与字符流;

import java.io.*;

public class InputStream字节输入流 {
    public static void main(String[] args) throws IOException {
        File file = new File("F:"+File.separator+"Test"+File.separator+"test.txt");
        InputStream input = new FileInputStream(file);
        byte[] data = new byte[1024];   //开辟一个缓冲区读取数据
       int length = input.read(data);   //读取数据,数据保存在字节数组之中,返回读取个数
        System.out.println(new String(data,0,length));  //从0开始到字节数组长度转换成字符串
        input.close();
    }
}

www.baidu.comwww.baidu.comwww.baidu.comwww.baidu.comwww.baidu.comwww.baidu.com

At this time, the contents of the file have been read out

The most troublesome problem in the input stream is that when using the read() method, it can only be received as a byte array.

A new method has been added to the InputStream class since JDK1.9:

Read all bytes: public byte[] readAllBytes() throws IOException

package 字节流与字符流;

import java.io.*;

public class InputStream字节输入流 {
    public static void main(String[] args) throws IOException {
        File file = new File("F:"+File.separator+"Test"+File.separator+"test.txt");
        InputStream input = new FileInputStream(file);
        byte[] data = input.readAllBytes();   //读取数据,数据保存在字节数组之中,返回读取个数
        System.out.println(new String(data));  //从0开始到字节数组长度转换成字符串
        input.close();
    }
}

If the content to be read is very large, then this reading will directly cause the program to crash.

Guess you like

Origin blog.csdn.net/weixin_46245201/article/details/112770388