java.ip.File類用于表示檔案(目錄)
File類隻用于表示檔案(目錄)的資訊(名稱、大小等),不能用于檔案内容的通路
RandomAccessFile java 提供對檔案内容的通路,既可以讀檔案,也可以寫檔案
java檔案模型
在硬碟上的檔案是byte byte byte存儲的,是資料的集合
打開檔案
有兩種模式 rw(讀寫) r(讀)
RandomAccessFile raf = new RandomAccessFile(file, “rw”)
檔案指針,打開檔案時指針在開頭pointer = 0;
寫檔案
raf.write(int) —>隻寫一個位元組(後8位),同時指針指向下一個位置,準備再次寫入
讀方法
int b = raf.read() ---->讀一個位元組
檔案讀寫完成以後一定要關閉
/********************
位元組流、字元流
1.位元組流
-
InputStream/OutputStream
InputStream抽象了應用程式讀取資料的方式
OutputStream抽象了應用程式寫出資料的方式
- EOF = End 讀到-1就讀到結尾
-
輸入流基本方法
int b = in.read();讀取一個位元組無符号填充到int低8位
int.read(byte[] buf)
in.read(byte[] buf,int start,int size)
4)輸出流基本方法
out.write(int b)寫出一個byte到流,b的低8位
out.write(byte[] buf)将buf位元組數組都寫入到流
out.write(byte[] buf,int start,int size)
FileInputStream —>具體實作了在檔案上讀取資料
FileOutputStream
DataOutputStream/DataOutputStream
對“流”功能的擴充,可以更加友善的讀取int,long,字元等類型資料
DataOutputStream
writeInt()/writeDouble()/writeUTF()
字元流
1)編碼問題
2)認識文本和文本檔案
位元組字元轉換流
FileInputStream in = new FileInputStream(“xxx”)
InputStreamReader isr = new InputStreamReader(in,“utf-8”)
FileOutputStream out = new FileOutputStream(“xxx”)
OutputStreamWriter osw = new OutputStreamWriter(out,“utf-8”)
字元流之檔案讀寫流
FileReader fr = new FileReader(“xxx”)
FileWrite fw = new FileWrite(“xxx”)
字元流的過濾器(一行一行讀取)
BufferedWriter
BufferedReader br = new BufferedReader() —> readLine 一次讀一行
BufferedWriter bw = new BufferedWriter()