600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > (字节流与字符流)InputStream字节输入流

(字节流与字符流)InputStream字节输入流

时间:2021-05-23 16:48:42

相关推荐

(字节流与字符流)InputStream字节输入流

与OutputStream类对应的是资杰输入流,InputStream主要是实现的就是字节数组读取。

public abstract class InputStream extends Object implements Closeable

在OutputStream里面定义有如下几个核心方法:

读取单个字节数据:public abstract int read() throws IOException (返回具体的字节数据,如果现在已经读取到底了返回-1)读取一组字节数据:public int read​(byte[] b) throws IOException 最常用 (读取一组字节数组,返回的是读取的个数,如果没有数据已经读取到底了则返回-1)读取一组字节数据部分内容(off-len):public int read​(byte[] b, int off, int len) throws IOException

IputStream类属于一个抽象类,这时应该依靠它的子类来实例化对象,如果要从文件读取一定使用FileInputStream子类,对于子类而言只关心父类对象的实例化,构造方法:public FileInputStream​(File file) throws FileNotFoundException

范例:读取数据

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();}}

这时已经将文件中的内容读取出来了

对于输入流里面最为麻烦的问题就在于使用read()方法读取的时候只能只能够以字节数组进行接收。

从JDK1.9开始在InputStream类里面增加了一个新的方法:

读取全部字节: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();}}

如果现在要读取的内容很大,那么这种读取会直接使程序崩溃。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。