標籤:
1.介紹
在實際開發過程中經常會用到資料的輸入/輸出操作,本篇部落格著重分析一下,java中經常用到的有關IO操作的類。而在java中可以將常用的流分為兩個部分:位元組流和字元流。
1.流的抽象基類
|
位元組流 |
字元流 |
| 輸入資料流 |
InputStream |
Reader |
| 輸出資料流 |
OutPutStream |
Writer |
正如表格所示,字元和位元組流都有自己的基類,其餘的都是繼承基類的擴充流的操作。下面會著重的講解一下。(只要會了字元流,位元組流與其操作一樣,只不過操作的檔案類型不一致而已)
2.字元流
專門用於讀寫文本資料,凡是可以用記事本開啟的檔案例如txt、java、html都資料字元流的操作範圍
1.字元輸出資料流——FileWriter
字元輸出資料流一般應用的是FileWriter,然後調用其建構函式,傳遞字串的檔案名稱,將字元寫在這個檔案中。其次調用父類方法Write(String str)寫字串,在這裡需要注意的是字元流寫資料,不會直接寫在目的檔案中,而是寫在記憶體中,必須走一個方法,重新整理,將記憶體中的資料重新整理到目的檔案中,字元流寫資料必須重新整理。一般調用的是Void Flush()方法,最後用完後需要關閉流對象。
<span style="font-family:SimSun;font-size:18px;"><span style="font-family:SimSun;font-size:18px;">package com.IO;import java.io.FileWriter;import java.io.IOException;public class FileWriterDemo1 {public static void main(String[] args) {FileWriter fw = null;try {//採用這種形式的話,每次都會覆蓋以前的資料資訊//fw=new FileWriter("c:\\exception.txt");//採用這種構造器的話,將會採用追加的形式添加資料。//查詢本機預設編碼錶示GBKfw=new FileWriter("c:\\exception.txt",true);fw.write("abd");fw.flush();fw.write("弄H啊哦嗎");fw.flush();} catch (IOException e) {e.printStackTrace();throw new RuntimeException("檔案寫入失敗");}finally{try {//必須在這裡進行判斷否則,報錯,可能會報null 指標的異常資訊。if(fw!=null){fw.close();}} catch (IOException e) {e.printStackTrace();throw new RuntimeException("關閉資源失敗");}}}}</span></span>
FileWriter寫文字檔操作如下
單個字元的形式,調用的父類Write(int c)方法
<span style="font-family:SimSun;font-size:18px;"><span style="font-family:SimSun;font-size:18px;">package cn.Io.iostream;import java.io.*;class FileWriterDemo1 {public static void main(String[] args) {//建立輸出資料流對象 FileWriter fw = null;try{ fw = new FileWriter("c:\\1.txt"); fw.write("abc"); fw.flush(); fw.write("adb"); //將記憶體中的資料重新整理到檔案中 fw.flush();}catch(IOException e){ e.printStackTrace(); throw new RuntimeException("寫入資料失敗");}finally{ try{ if(fw!=null) fw.close();}catch(IOException e){ e.printStackTrace(); throw new RuntimeException("關閉流對象失敗");}}}}</span></span>
字元數組的形式,調用的方法如下
~write(char[] ch)傳遞整個字元數組
~write(char[] ch,int off,int len)寫數組的一部分,off開始下標,len個數
<span style="font-family:SimSun;font-size:18px;"><span style="font-family:SimSun;font-size:18px;">package cn.IO.iostream;/* * FileWriter以數組的形式寫入檔案 * */import java.io.*;public class FileWriterDemo2 {public static void main(String[] args) throws IOException {//調用此輸出資料流的建構函式,將會以追加的形式寫入到檔案內容中FileWriter fw = new FileWriter("c:\\demo.txt",true);fw.write(97);char[] ch= {'a','b','c'};fw.write(ch,1,1);fw.write("sefser");fw.flush();fw.close();}}</span></span>
注意,如果要想檔案中追加寫入內容,而不是覆蓋原來的內容的話,只需在建立輸入資料流對象的時候,調用其
FileWriter(String fileName, boolean append)構造方法即可
2.字元輸入資料流
字元輸入資料流一般應用的是FileReader讀取文字檔,然後調用其構造方法,建立輸入資料流對象,傳遞字元檔案名稱,例如new FileReader(‘檔案名稱‘),讀取一個字元 int read()方法,每次唯讀取一個字元,然後指定的read()方法,會自動的向後讀取一個,讀到末尾的時候,將會返回-1
讀取單個字元
<span style="font-family:SimSun;font-size:18px;"><span style="font-family:SimSun;font-size:18px;">package cn.IO.iostream;/* * 採用字元輸入資料流對象,進行讀取檔案操作 */import java.io.*;public class FileReaderDemo {public static void main(String[] args) throws IOException{//建立輸入資料流對象FileReader fr = new FileReader("c:\\demo.txt");//調用Read方法,每次唯讀取一個字元操作int x = 0;while((x = fr.read())!=-1){System.out.print((char)x);}fr.close();}} </span></span>
讀取字元數組操作
int read(char[] cbuf):讀取方法,傳遞字元數組,返回值int代表有效讀取的字元個數,此方法讀取效率高
<span style="font-family:SimSun;font-size:18px;"><span style="font-family:SimSun;font-size:18px;">package cn.itcast.iostream;/* * 採用字元輸入資料流對象進行字元數組的讀取 */import java.io.*;public class FileReaderDemo1 {public static void main(String[] args) throws IOException{FileReader fr = new FileReader("c:\\demo.txt");//建立一個字元數組char[] ch = new char[1024];//一般是1024的倍數int x = 0 ;while(( x = fr.read(ch))!=-1){//String(char[] value, int offset, int count) System.out.print(new String(ch,0,x));}fr.close();}}</span></span>
複製檔案操作
利用字元流的輸入和輸出資料流,來操作檔案的複製功能
第一種方式,讀一個字元,寫一個字元
<span style="font-family:SimSun;font-size:18px;"><span style="font-family:SimSun;font-size:18px;">package cn.IO.iostream;/* * 採用字元流來實現複製的功能 */import java.io.*;public class CopyText {public static void main(String[] args) {long start = System.currentTimeMillis();//建立字元輸入和輸出資料流的對象FileReader fr = null;FileWriter fw = null;try{//分別調用其建構函式fr = new FileReader("c:\\demo.txt");fw = new FileWriter("d:\\demo.txt");//定義變數來報錯單個字元讀取的值int len = 0 ;while((len = fr.read())!=-1){fw.write(len);fw.flush();}}catch(IOException e){throw new RuntimeException("複製失敗");}finally{try{if(fw!=null)fw.close();}catch(IOException e){throw new RuntimeException("關閉寫入流失敗");}finally{try{if(fr!=null)fr.close();}catch(IOException e){throw new RuntimeException("關閉輸入資料流失敗");}}}long end = System.currentTimeMillis();System.out.println(end - start);}}</span></span>
第二種方法:讀一個字元數組,寫一個字元數組
<span style="font-family:SimSun;font-size:18px;"><span style="font-family:SimSun;font-size:18px;">package cn.IO.iostream;/* *採用輸入和輸出資料流完成複製的功能操作 */import java.io.*;public class CopyText2 {public static void main(String[] args) {long start = System.currentTimeMillis();//分別建立字元輸入和輸出資料流對象FileReader fr = null;FileWriter fw = null;try{//分別調用其建構函式執行個體化fr = new FileReader("c:\\e.html");fw = new FileWriter("d:\\1.html");//定義要讀取的字元數組char[] ch = new char[1024];int len = 0 ;while((len = fr.read(ch))!=-1){fw.write(ch,0,len);fw.flush();}}catch(IOException e){throw new RuntimeException("複製失敗");}finally{try{if(fw!=null)fw.close();}catch(IOException e){throw new RuntimeException("關閉輸出資料流失敗");}finally{try{if(fr!=null)fr.close();}catch(IOException e){throw new RuntimeException("關閉輸入資料流失敗");}}}long end = System.currentTimeMillis();System.out.println(end - start);}}</span></span>
注意:利用讀取字元數組的形式,效率會快很多
3.緩衝流
在讀寫的時候,也可以採取緩衝流的形式對字元或者位元組進行緩衝,從而實現字元、數組和行的高效讀寫操作。
|
字元 |
位元組 |
| 緩衝輸入資料流 |
BufferedReader |
BufferedInputStream |
| 緩衝輸出資料流 |
BufferedWriter |
BufferedOutputStream |
主要是在緩衝流中可以採取讀取一行方式,來操作源檔案。
所有的操作都是一致的,都是通過構造方法的形式,傳遞字元或者位元組流,例如BufferedReader(Reader r),來傳遞進去FileReader,通過String ReadLine()方法來讀取檔案的一行,當讀到檔案末尾的時候,將返回null值
<span style="font-family:SimSun;font-size:18px;">package com.IO;import java.io.BufferedReader;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;/* * 字元輸入資料流,BufferedReader,讀取文本一行的功能 */public class BufferedReaderDemo {public static void main(String[] args) throws IOException {//建立字元輸入資料流緩衝區對象,傳遞字元輸入對象BufferedReader bfr=new BufferedReader(new FileReader("c:\\1.txt"));//開始讀取文本一行,返回stringString line=bfr.readLine();System.out.println(line);}}</span>
其餘的BufferedInputStream、BufferedOutPutStream、BufferedReader、BufferedWriter用法一致,參照上面寫法即可。
採用緩衝流實現檔案複製的效果。
<span style="font-family:SimSun;font-size:18px;">package com.IO;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import javax.management.RuntimeErrorException;/* * 利用字元流緩衝區來賦值 * 讀寫行,寫換行 */public class CopyTest2 {public static void main(String[] args) {// 匿名對象的形式,建立流對象和緩衝去對象BufferedReader bfr = null;BufferedWriter brw = null;try {bfr = new BufferedReader(new FileReader("c:\\1.txt"));brw = new BufferedWriter(new FileWriter("c:\\2.txt"));// 讀取一行,寫一行,寫換行String line = null;while ((line = bfr.readLine()) != null) {brw.write(line);//進行換行的功能brw.newLine();brw.flush();}} catch (Exception e) {e.printStackTrace();throw new RuntimeException("複製失敗");}finally{try {if(bfr!=null){bfr.close();}} catch (IOException e2) {throw new RuntimeException("寫入關閉失敗");}finally{try {if(brw!=null){brw.close();}} catch (IOException e3) {throw new RuntimeException("讀入關閉失敗");}}}}}</span>
4.轉換流
Java中的轉換流一般有兩個分別是,OutPutStreamWriter、InputStreamReader,是字元流通向位元組流的橋樑。
正如所示,通過緩衝流就可以把位元組流轉換成為字元流來處理,通過緩衝區一封裝,就可以讀取行的操作了。
<span style="font-family:SimSun;font-size:18px;">package com.IO;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;public class TranseDemo3 {public static void main(String[] args) throws IOException {/*//控制台輸入的位元組流InputStream in=new FileInputStream("c:\\1.java");//建立轉換流對象,傳遞位元組輸入資料流InputStreamReader isr=new InputStreamReader(in);//既然已經將in轉換成了字元流isr,可以使用字元流緩衝區對象BufferedReader,行讀取BufferedReader bfr=new BufferedReader(isr);OutputStream out=System.out;OutputStreamWriter osw=new OutputStreamWriter(out);BufferedWriter bfw=new BufferedWriter(osw);*/BufferedReader bfr=new BufferedReader(new InputStreamReader(System.in));BufferedWriter brw=new BufferedWriter(new OutputStreamWriter(System.out));String line=null;while ((line=bfr.readLine())!=null) {brw.write(line);brw.flush();brw.newLine();}brw.close();bfr.close();}}</span>
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
Java學習筆記六(I/O流)