InputStream所有的所有

/*
java.io.InputStream
java.io.FileInputStream,文件字节输入流

按照字节方式读取文件
*/
import java.io.*;
public class fuck1{
public static void main(String[] args){

FileInputStream fls=null;

//1.要读取某个文件,先与这个文件创建一个输入流
//路径分为绝对路径和相对路径
//String filepath="c:\\";绝对路径
//因为\是转义字符,有特殊意义需要用两个,或者用/
try{
String filepath="love.txt";
fls=new FileInputStream(filepath);

//2.开始读

int i1=fls.read();//以字节的方式读取
System.out.println(i1);//97
//如果已经读取到文件末尾,就会返回-1

}
catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e2){//小异常放上面,大异常放下面
e2.printStackTrace(); //可以连续捕捉异常,不过要注意范围问题
}finally{
//为了保证流一定会被释放,所以在finally语句块中执行
if(fls!=null){
try{
fls.close();
}catch(IOException e1){
e1.printStackTrace();
}

}
}


}
}


//以下程序存在缺点:频繁访问磁盘,伤害磁盘,并且效率低
//偷懒直接扔出大异常
public static void main(String[] args)throws Exception{

//1.创建流
FileInputStream fls=new FileInputStream("love.txt");

//2.开始读
while(true){
int temp=fls.read();
if(temp!=-1){
System.out.println(temp);
}else{
break;
}
}

//升级循环
int temp=0;
while((temp=fls.read())!=-1){
System.out.println(temp);
}

fls.close();

}



/*

int read(byte[] bytes)
读取之前在内存中准备一个byte数组,每次读取多个字节存储到byte数组中
一次读取多个字节,不是单字节读取了
 
效率高
*/
import java.io.*;
public class fuck{

public static void main(String[] args)throws Exception{
//1.创建输入流
FileInputStream fls=new FileInputStream("love.txt");

//2.开始读
//准备一个byte数组
byte[] bytes=new byte[3];//每一次最多读取3个字节
 
//搞清楚方法的返回类型和参数类型
//该方法返回的int类型的值,代表的是这次读取了多少个字节
int i1=fls.read(bytes);//3
//将bytes数组转换成String类型
System.out.println(new String(bytes));//ilo

int i2=fls.read(bytes);//3
System.out.println(new String(bytes));//vey

int i3=fls.read(bytes);//2,只覆盖了前两个字节,后一个字节不变
//为什么是i3,i3就代表这次读取字节数量,刚好是从0开始
//跟这个配一脸
System.out.println(new String(bytes,0,i3));//ou
//System.out.println(new String(bytes));ouy

int i4=fls.read(bytes);//-1//已到达文件的末尾
System.out.println(new String(bytes));ouy

System.out.println(i1);
System.out.println(i2);
System.out.println(i3);
System.out.println(i4);

}

}



/*
循环读取
*/


import java.io.*;


public class fuck2{

public static void main(String[] args)throws Exception{

FileInputStream fls=new FileInputStream("love.txt");

/*
byte[] bytes=new byte[3];//每次读取3个字节
while(true){
int temp=fls.read(bytes);
if(temp==-1) break;

//将bytes数组中有效的部门转换成字符串
System.out.println(new String(bytes,0,temp));
}
*/

//升级循环
/*int temp=0;
while(temp=fls.read(bytes)!=-1){
System.out.println(new String(bytes,0,temp));
}

fls.close();*/

System.out.println(fls.available());//8
System.out.println(fls.read());//105

//返回流中剩余的估计字节数
System.out.println(fls.available());//7

//跳过两个字节
fls.skip(2);
System.out.println(fls.read());//118
fls.close();
}

}

猜你喜欢

转载自blog.csdn.net/rolic_/article/details/80379896
今日推荐