Java之字节输入流InputStream

来源:互联网 发布:java在线音乐网站源码 编辑:程序博客网 时间:2024/06/10 21:24
import java.io.*;/*字节输出流  InputStream  ->abstract(抽象)类型该类中有两个接口  Closeable -> 关闭(与OutputStream一样不考虑)读取的方法:1. 读取单个字节:public abstract int read() throw IOException返回读取的字节内容,如果没有已经内容则返回 -12. 将读取的数据保存在字节数组里:public int read(byte[]b)  throw IOException 返回读取的数据长度;,但是如果读取到结尾了返回 -13. 将读取的数据保存在部分字节数组里:public int read(byte[]b,int off, int len)  throw IOException返回读取的部分数据的长度,如果已经读取到结尾返回 -1*/public class testDemo{public static void main(String args[]) throws IOException{//定义要输出的文件的一个路径File file  = new File("e:" + File.separator +"Demo"+File.separator+ "text.txt");if(file.exists()){//文件存在InputStream input = new FileInputStream(file);byte data[] = new byte[1024];int len = input.read(data); //将部分内容保存在字节数组里面/*String str = new String(data,0,len);System.out.println(str);*///下面单个字节读取(采用while()循环)int foot = 0;//表示字节数组的操作角标int temp = 0;//表示接受每次读取的字节数据while(input.read() != -1){ //读取一个字节并判断是否有内容data[foot++] = (byte)temp;temp = input.read(); //读取一个字节}System.out.println(new String(data,0,len));input.close();}}}

0 0
原创粉丝点击