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

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章