33 檔案IO流(二)
1 IO流分類
分類依據:
? 流向程式里面還是流到程式外面
分類結果:(以最基礎的舉例)
A 、輸入流
? 位元組輸入流 File(來源)InPutStream
a. 作用:
? 從指定地址的檔案讀取資料到程式中
b. 具體操作方法
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class TestRead {
public static void main(String[] args) {
File file=new File("C:\\Users\\SSS翱翔萬里\\Desktop\\測驗.txt");
//首先你得判斷它是否是檔案
if(file.isFile()){
//如果是,就讀取它里面的內容
FileInputStream fileInputStream=null;
byte[] bytes=null;
try {
fileInputStream = new FileInputStream(file);
int length=0;
bytes= new byte[1024*8];
while((length=fileInputStream.read(bytes))!=-1){
System.out.print(new String(bytes,0,length));
//bytes陣列存放的資料,最后一次可能不為滿,
//所以長度為每次的有效長度是最好的
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
//finally中的陳述句是無論有無例外都會執行完的
//注意:雖然不關閉流,系統會自動幫你關閉且一般不會報錯,但還是建議按標準流程來
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
System.out.println("給的地址不是一個檔案");
}
}
}
c.運行截圖
B、輸出流
? 位元組輸入流 File(來源)OutPutStream
a.作用:
? 把程式中的資料寫到指定的檔案里頭
b.具體操作:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
public class TestWrite {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("請輸入你要寫入的字串");
String str=scanner.next();
File file=new File("C:\\Users\\SSS翱翔萬里\\Desktop\\測驗.txt");
//首先你得判斷它是否是檔案
if(file.isFile()){
//如果是,就開始下面的往里面去寫的操作
FileOutputStream fileOutputStream=null;
byte[] bytes=null;
try {
//如果不寫true,則默認是覆寫原來的內容
fileOutputStream = new FileOutputStream(file,true);
//因為是位元組流,所以得把字串轉換成bytes[]陣列
fileOutputStream.write(str.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
finally {
//finally中的陳述句是無論有無例外都會執行完的
//注意:雖然不關閉流,系統會自動幫你關閉且一般不會報錯,但還是建議按標準流程來
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
System.out.println("給的地址不是一個檔案");
}
}
}
c.運行截圖:

(1)

(2)

(3)
2. 總結
-
輸入流和輸出流都是需要關閉的.(為防止忘記寫,在建立實體化完流物件操作時,就在下面一行寫該物件的關閉操作)
-
為了防止輸入流和輸出流的源頭不存在,會拋出FileNotFoundException例外,可以人為的去加個if條件判斷
-
對檔案進行輸出流操作時,默認為覆寫操作,若想追加,直接令呼叫構造方法,傳遞的引數除了檔案物件(含有檔案的地址資訊),后面再加上true;
fileOutputStream = new FileOutputStream(file,true);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/232850.html
標籤:Java
上一篇:4 自動裝配
下一篇:5 使用注解開發
