大佬的理解->《Java IO(三) -- 位元組流》
1、FileInputStream
1.1 初始化
| FileInputStream(String name) |
|---|
| FileInputStream(File file) |
//直接通過檔案地址初始化
FileInputStream fis = new ileInputStream("D:/test/test1.txt");
//通過File物件初始化
File file = new File("D:/test/test1.txt");
FileInputStream fis = new FileInputStream(file)
1.2 獲取檔案大小
available()
FileInputStream fis = new ileInputStream("D:/test/test1.txt");
fis.available(); //檔案大小
1.3 讀取檔案內容
| read() | 讀取一個位元組(回傳對應位元組的ascii碼值) |
|---|---|
| read(byte b[]) | 根據位元組緩沖陣列的長度,進行讀取(回傳讀取的位元組數) |
read()
//檔案 D:/test/test1.txt
內容
KH96abcdefghijk
FileInputStream fis = new ileInputStream("D:/test/test1.txt");
while (true){
//read() 方法:從輸入流物件中,一次讀取一個位元組(回傳的是對應位元組的ascii碼值,int型別)
int hasRead = fis.read();
//當讀取到末尾,回傳-1,代表檔案讀取結束
if(hasRead == -1){
break;
}
System.out.print((char) hasRead);
//列印檔案中字符的ascii值
//轉化為字符:KH96abcdefghijk
}
//最后一定要關閉資源
fis.close();
運行結果:
源檔案的大小:15
KH96abcdefghijk
read(byte b[])
帶緩沖位元組數,讀取檔案內容,一次讀取就不是一個位元組,而是根據位元組緩沖陣列的長度,進行讀取
錯誤案例
讀取時通過read()來判斷是否繼續回圈,讀取到錯誤值
FileInputStream fis = new ileInputStream("D:/test/test1.txt");
//帶緩沖位元組數,根據位元組緩沖陣列的長度,進行讀取
byte[] bytes = new byte[5];
//容易出錯的判斷方式:read()方式執行一次,就讀取一個位元組(沒有保存,讀完就扔,位元組丟失),不可以作為判斷條件
while(fis.read() != -1){
//回圈讀取內容
//帶緩沖陣列的讀取,方法回傳的是讀取的位元組數,不是讀取的內容
//每次讀取的資料,是由緩沖位元組陣列長度決定,每次都是從上一次讀取的位置后開始繼續讀取,每次都是將讀取的內容依次放入快取陣列
int hasRead = fis.read(bytes);
System.out.println("讀取的位元組數:"+hasRead);
System.out.println(new String(bytes));
System.out.println("讀取檔案成功");
}
fis.close();
運行結果:
源檔案的大小:15
讀取的位元組數:5
H96ab //K丟失
讀取檔案成功
讀取的位元組數:5
defgh //c丟失
讀取檔案成功
讀取的位元組數:2
jkfgh //i丟失,并且還多出了上一次留下 dgh,這是因為沒有讀滿緩沖位元組陣列,而造成的讀取上一次的值
讀取檔案成功
正確案例
因為帶位元組緩沖陣列回傳的時讀取到的長度,所以,用讀取到的長度來判斷是否要繼續讀取,和要寫入多少個位元組
FileInputStream fis = new ileInputStream("D:/test/test1.txt");
//帶緩沖位元組數,根據位元組緩沖陣列的長度,進行讀取
byte[] bytes = new byte[5];
//正確寫法
int hasRead = 0;
while((hasRead = fis.read(bytes)) > 0){
//每次讀取的內容
System.out.println(new String(bytes,0,hasRead));
}
fis.close();
運行結果:
源檔案的大小:15
KH96a
bcdef
ghijk
// 沒有丟失位元組
1.4 資源關閉
close();
? 在使用流資源的時候一定要關閉資源,否則會造成資源浪費;
放在try( ) 里面
? JDK1.7以后,只需將資源初始化放在try()里面就可以不用手動關閉流資源;
2、FileOutputStream
2.1初始化
| FileOutputStream(File file) |
|---|
| FileOutputStream(File file, boolean append) |
| FileOutputStream(String name) |
| FileOutputStream(String name, boolean append) |
與FileInputStream類似,不過寫入的檔案不一定要存在,如果檔案不存在,會自動創建一個空的檔案;
2.2 寫入方式 boolean append
boolean append 使用否以追加方式方式寫入;
false(默認值,覆寫)
true(追加)
2.3 寫入檔案內容
| write(byte b[]) |
|---|
| write(byte b[], int off, int len) |
String string = "KH96班,正在學習檔案輸出流,輸出檔案2";
//File file = new File("D:/test/test2.txt");
//JDK1.7以后,只需將資源初始化放在try()里面就可以不用手動關閉流資源,推薦使用;
try(FileOutputStream fos = new FileOutputStream("D:/test/test2.txt",true)){
//將字串轉成位元組陣列,寫入目標檔案
fos.write(string.getBytes());
//手動重繪緩沖區
fos.flush();
}catch (IOException e){
e.printStackTrace();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/492488.html
標籤:其他
