標籤:int char throws 瞭解 [] ring 方法 try inf
以stream結尾的稱為萬能流(位元組流),否則為字元流
1.java流的概述:
檔案通常是由一串的位元組或字元組成,組成檔案的位元組序列稱為位元組流,組成檔案的字元序列稱為字元流。
2.Java中根據流的方向可以分為:輸入資料流和輸出資料流
輸入資料流:輸入資料流是將檔案或其他輸入裝置的資料載入到記憶體的過程
輸出資料流:輸出資料流是將記憶體中的資料儲存到檔案或其他輸入裝置中
??????3.檔案是由位元組或字元構成,那麼將檔案載入到記憶體或者將檔案輸出到檔案,需要輸入資料流和輸出資料流的支援,那麼在JAVA語言中又把輸入和輸出資料流分為兩種:
位元組輸入資料流、位元組輸出資料流 字元輸入資料流、字元輸出資料流
3.1 Inputstream(位元組輸入資料流):inputstream是一個抽象的類,所有實現了inputstream類的都是位元組輸入資料流,主要瞭解一下子類即可:
範例:
public class Test{
public static void main(String[] args) throws Exception{
//建立一個輸入資料流
InputStream in=new FileInputStream("c:/a.txt");
//定義一個臨時變數
int temp=0;
while((temp=in.read())!=-1){
System.out.println((char)temp);
}
}
}
3.2 OutputStream(位元組輸出資料流):OutputStream是一個抽象的類,所有實現了這個類的都是位元組輸出資料流
如果調用了close()方法,那麼會自動調用flush()方法,但是建議手動顯示的去調用flush()方法
範例:
public class Test {
public static void main(String[] args) {
//建立一個輸出位元組流
OutputStream out = null;
try {
out = new FileOutputStream("c:/b.txt");
out.write(123);
//必須調用flush或close
out.flush();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("success");
}
}
jdk1.8新特性自動關閉:
範例:
public class Test{
public static void main(String[] args){
try(OutputSreeam out =new FileOutputStream("c:/c.txt");){
//建立一個輸出位元組流
out.write(1);
//必須調用flush方法
out.flush();
}catch(Exception e){
e.printStackTrace();
}
System.out.println(success);
}
}
IO流-----(位元組流)