I/O程式設計
1.檔案操作
1.1File類的使用
- 建立/删除/存在
注意!:每個檔案系統對檔案的分隔符不同,是以可以使用file類中的
File.separator #自動獲得路徑分隔符
- 擷取檔案的元資訊
File.listFiles() #列出目錄中的全部檔案資訊
1.2位元組流和字元流
- 位元組流:OutputStream(寫),inputStream(讀)
- 字元流:Reader,Wirter
檔案操作步驟
- 讀取檔案
- 對位元組流或者字元流執行個體化
- 執行讀/寫
- 關閉所有的流
1.2.1 OutputStream
OutputStream的繼承關系圖
從這個繼承關系圖可以看出OutputStram是一個抽象類,是以需要使用位元組輸出流的時候,一般都是用他的子類FileOutputStream
構造方法
FileOutputStream(File file) | 建立一個檔案輸出流寫入指定的 對象表示的檔案。 |
---|---|
FileOutputStream(File file, boolean append) | 建立一個檔案輸出流寫入指定的 對象表示的檔案。 |
FileOutputStream(String name) | 建立一個檔案輸出流,用指定的名稱寫入檔案。 |
FileOutputStream(String name, boolean append) | 建立一個檔案輸出流,用指定的名稱寫入檔案,參用追加或者覆寫的方式 |
方法
close() | 關閉此檔案輸出流并釋放與此流關聯的任何系統資源。 |
---|---|
write(byte[] b) | 寫 位元組從指定的位元組數組來此檔案輸出流。 |
write(byte[] b, int off, int len) | 寫 位元組指定位元組數組中的起始偏移 此檔案輸出流。 |
write(int b) | 将指定的位元組寫入該檔案輸出流中。 |
提示
使用AutoCloseable自動關閉接口
由于OutputStream是AutoCloseable的子類,是以可以使用try-catch來實作自動關閉
try{
File file = new File("");
FileOutputStream fileOutputStream = new FileOutputStream(file);
String str = "Hello";
fileOutputStream.write(str.getBytes());
}catch (Exception e){
e.printStackTrace();
}
1.2.2InputStream
InputStream的繼承關系圖
方法
close() | 關閉此檔案輸入流并釋放與流關聯的任何系統資源。 |
---|---|
read() | 從這個輸入流讀取一個位元組的資料。 |
read(byte[] b) | 讀到 從輸入流到位元組數組資料位元組。 |
read(byte[] b, int off, int len) | 讀到 從輸入流到位元組數組資料位元組。 |
skip(long n) | 跳過并丢棄 位元組輸入流中的資料。 |
從這個繼承關系圖可以看出InputStram是一個抽象類,是以需要使用位元組輸出流的時候,一般都是用他的子類FileInputStream
測試
File file = new File("");
FileInputStream fileInputStream = new FileInputStream(file);
byte[] data = new byte[1024];
int len = fileInputStream.read(data);
//位元組轉成字元串
System.out.println(new String(data,0,len));
可以一步讀完這個檔案的所有數組data防止資料越界
InputStream input = new FileInputStream(file);
input.readAllBytes();
1.2.3 Writer
Writer的繼承關系圖
方法
append(char c) | 追加輸出内容 |
---|---|
close() | 關閉流,沖洗它 |
flush() | 沖流緩沖區 |
write(char[] cbuf) | 寫一個字元數組。 |
write(char[] cbuf, int off, int len) | 寫入一個字元數組的一部分。 |
write(int c) | 寫一個字元。 |
write(String str) | 寫一個字元串。 |
write(String str, int off, int len) | 寫入字元串的一部分。 |
1.2.4 Reader
Reader的繼承關系圖
方法
skip(long n) | 跳過的字元。 |
---|---|
read() | 讀取單個字元。 |
close() | 關閉流并釋放與它相關聯的任何系統資源。 |
mark(int readAheadLimit) | 标記流中的目前位置。 |
read(char[] cbuf) | 将字元讀入一個數組。 |
read(char[] cbuf, int off, int len) | 将字元讀入一個數組的一部分。 |
read(CharBuffer target) | 試圖将字元讀入指定的字元緩沖區中。 |
1.2.5位元組流和字元流的差別
雖然在java.io包内都存在字元流和位元組流,但是在資料傳輸(或者将資料存儲在磁盤的時候),位元組流資料能直接存在磁盤中,而字元流資料需要先暫存到緩沖區中,然後通過FLushable接口中提供的flush()方法,将資料強制重新整理緩沖區的資料,才會有内容輸出,否則不會有内容輸出