|
1. File類(lèi) File 類(lèi)的主要方法有: getName(),getCanonicalFile(),lastModified(),isDerector(),isFile(),getPath() 等; 2 )File 類(lèi)與 FileInputStream 類(lèi)的區別:
流類(lèi)關(guān)注的是文件內容,而 File 類(lèi)關(guān)注的是文件在磁盤(pán)上的存儲。
File 不屬于文件流 , 只能代表一個(gè)文件或是目錄的路徑名而已。 如果處理文件或者目錄名,就應該使用 File 對象,而不是字符串。 2. FileInputStream 類(lèi) 1 ) FileInputStream 類(lèi)介紹: 以字節為單位(非 unicode )的流處理。字節序列即:二進(jìn)制數據。與編碼無(wú)關(guān),不存在亂碼問(wèn)題。 FileInputStream 類(lèi)的主要方法有: Read (), read ( byte[] b ), read ( byte[],int off,int len ) ,available();
2 ) FileInputStream 類(lèi)與 FileReader 類(lèi)的區別: 兩個(gè)類(lèi)的構造函數的形式和參數都是相同的,參數為 File 對象或者表示路徑的 String ,它們到底有何區別 呢? FileInputStream :以字節流方式讀??; FileReader :把文件轉換為字符流讀入; 來(lái)的是char數組或者String ,使用InputStream讀取出來(lái)的是byte數組。
流的讀取byte(8位),所以FileReader類(lèi)是將文件按字符流的方式讀取,FileInputStream則按字節流的方 式讀取文件;InputStreamReader可以將讀如stream轉換成字符流方式,是reader和stream之間的橋梁.
FileInputStream 類(lèi)以二進(jìn)制輸入 / 輸出, I/O 速度快且效率搞,但是它的 read ()方法讀到 的是一個(gè)字節(二進(jìn)制數據),很不利于人們閱讀。 而 FileReader 類(lèi)彌補了這個(gè)缺陷,可以以文本格式輸入 / 輸出,非常方便; 比如可以使用while((ch = filereader.read())!=-1 ) 循環(huán)來(lái)讀取文件;可以使用 BufferedReader 的 readLine() 方法一行一行的讀取文本。 當我們讀寫(xiě)文本文件的時(shí)候,采用 Reader 是非常方便的,比如 FileReader , InputStreamReader 和 BufferedReader 。其中最重要的類(lèi)是 InputStreamReader ,它是字節轉換為字符的橋 梁。 你可以在構造器重指定編碼的方式,如果不指定的話(huà)將采用底層操作系統的默認編碼方式,例如 GBK 等. FileReader 與 InputStreamReader 涉及編碼轉換 ( 指定編碼方式或者采用 os 默認編碼 ) ,可 能在不同的平臺上出現亂碼現象!而 FileInputStream 以二進(jìn)制方式處理,不會(huì )出現亂碼現象 . 3 )如果處理純文本文件,建議使用 FileReader ,因為更方便,也更適合閱讀;但是要注意編碼問(wèn)題! 用到很多,如將文件流是Stream的方式傳向服務(wù)器! 1) FileReader 類(lèi)介紹: InputStreamReader 類(lèi)的子類(lèi),所有方法( read ()等)都從父類(lèi) InputStreamReader 中繼承而來(lái); 2) 與 InputStreamReader 類(lèi)的區別: 該類(lèi)與它的父類(lèi) InputStreamReader 的主要不同在于構造函數,主要區別也就在于構造函數!從 InputStreamReader 的構造函數中看到,參數為 InputStream 和編碼方式,可以看出,當要指定編碼方式時(shí),必須使用 InputStreamReader 類(lèi);而 FileReader 構造函數的參數與 FileInputStream 同,為 File 對象或表示 path 的 String ,可以看出,當要根據 File 對象或者 String 讀取一個(gè)文件時(shí),用 FileReader ;我想 FileReader 子類(lèi)的作用也就在于這個(gè)小分工吧。 3) 一般用法: FileReader fr = new FileReader("ming.txt"); 4. InputStreamReader 類(lèi) 以文本格式輸入 / 輸出,可以指定編碼格式; 主要方法: getEncoding (),read(); 一般用法: InputStreamReader isr = new InputStreamReader(new FileInputStream("ming.txt")); 5. BufferedReader 類(lèi) BufferedReader 由Reader類(lèi)擴展而來(lái),提供通用的緩沖方式文本讀取,而且提供了很實(shí)用的readLine, 讀取分行文本很適合,BufferedReader是針對Reader的,不直接針對文件,也不是只針對文件讀取。 1) File file = new File ("hello.txt"); FileInputStream in=new FileInputStream(file); 2) File file = new File ("hello.txt"); FileInputStream in=new FileInputStream(file); InputStreamReader inReader=new InputStreamReader(in); BufferedReader bufReader=new BufferedReader(inReader); 3) File file = new File ("hello.txt"); FileReader fileReader=new FileReader(file); BufferedReader bufReader=new BufferedReader(fileReader); |
聯(lián)系客服