[Java] I/O流

>>  http://www.jb51.net/article/44684.htm

>>  http://blog.csdn.net/ilibaba/article/details/3955799

>>  http://www.cnblogs.com/rollenholt/archive/2011/09/11/2173787.html

IO流的分類
一、根據流的數據對象來分:
高端流:全部的內存中的流都是高端流,好比:InputStreamReader  
低端流:全部的外界設備中的流都是低端流,好比InputStream,OutputStream 
如何區分:全部的流對象的後綴中包含Reader或者Writer的都是高端流,反之,則基本上爲低端流,不過也有例外,好比PrintStream就是高端流html

 
 

二、根據數據的流向來分:
輸出流:是用來寫數據的,是由程序(內存)--->外界設備
輸入流:是用來讀數據的,是由外界設備--->程序(內存)
如何區分:通常來講輸入流帶有Input,輸出流帶有Output java

 
 

三、根據流數據的格式來分:
字節流:處理聲音或者圖片等二進制的數據的流,好比InputStream 
字符流:處理文本數據(如txt文件)的流,好比InputStreamReader  
如何區分:可用高低端流來區分,全部的低端流都是字節流,全部的高端流都是字符流python

 
 

四、根據流數據的包裝過程來分:
原始流:在實例化流的對象的過程當中,不須要傳入另一個流做爲本身構造方法的參數的流,稱之爲原始流。
包裝流:在實例化流的對象的過程當中,須要傳入另一個流做爲本身構造方法發參數的流,稱之爲包裝流。
如何區分:因此的低端流都是原始流,因此的高端流都是包裝流linux

 
 

IO流對象的繼承關係(以下圖):
web

 

Java IO 的通常使用原則 :  apache

1、按數據來源(去向)分類:windows

1 、是文件: FileInputStream, FileOutputStream, ( 字節流 )FileReader, FileWriter( 字符 )數組

2 、是 byte[] : ByteArrayInputStream, ByteArrayOutputStream( 字節流 )網絡

3 、是 Char[]: CharArrayReader, CharArrayWriter( 字符流 )dom

4 、是 String: StringBufferInputStream, StringBufferOuputStream ( 字節流 )StringReader, StringWriter( 字符流 )

5 、網絡數據流: InputStream, OutputStream,( 字節流 ) Reader, Writer( 字符流 )

2、按是否格式化輸出分:

1 、要格式化輸出: PrintStream, PrintWriter

3、按是否要緩衝分:

1 、要緩衝: BufferedInputStream, BufferedOutputStream,( 字節流 ) BufferedReader, BufferedWriter( 字符流 )

4、按數據格式分:

1 、二進制格式(只要不能肯定是純文本的) : InputStream, OutputStream 及其全部帶 Stream 結束的子類

2 、純文本格式(含純英文與漢字或其餘編碼方式); Reader, Writer 及其全部帶 Reader, Writer 的子類

5、按輸入輸出分:

1 、輸入: Reader, InputStream 類型的子類

2 、輸出: Writer, OutputStream 類型的子類

6、特殊須要:

1 、從 Stream 到 Reader,Writer 的轉換類: InputStreamReader, OutputStreamWriter

2 、對象輸入輸出: ObjectInputStream, ObjectOutputStream

3 、進程間通訊: PipeInputStream, PipeOutputStream, PipeReader, PipeWriter

4 、合併輸入: SequenceInputStream

5 、更特殊的須要: PushbackInputStream, PushbackReader, LineNumberInputStream, LineNumberReader

決定使用哪一個類以及它的構造進程的通常準則以下(不考慮特殊須要):

首先,考慮最原始的數據格式是什麼: 原則四

第二,是輸入仍是輸出:原則五

第三,是否須要轉換流:原則六第 1 點

第四,數據來源(去向)是什麼:原則一

第五,是否要緩衝:原則三 (特別註明:必定要注意的是 readLine() 是否有定義,有什麼比 read, write 更特殊的輸入或輸出方法)

第六,是否要格式化輸出:原則二

 【案例1】建立一個新文件
import java.io.*; class hello{ public static void main(String[] args) { File f=new File("D:\\hello.txt"); try{ f.createNewFile(); }catch (Exception e) { e.printStackTrace(); } } } 【運行結果】: 程序運行以後,在d盤下會有一個名字爲hello.txt的文件。 
【案例2】File類的兩個常量
import java.io.*; class hello{ public static void main(String[] args) { System.out.println(File.separator); System.out.println(File.pathSeparator); } } 【運行結果】: \ ; 此處多說幾句:有些同窗可能認爲,我直接在windows下使用\進行分割不行嗎?固然是能夠的。可是在linux下就不是\了。
因此,要想使得咱們的代碼跨平臺,更加健壯,因此,你們都採用這兩個常量吧,其實也多寫不了幾行。呵呵、

如今咱們使用File類中的常量改寫上面的代碼:
import java.io.*; class hello{ public static void main(String[] args) { String fileName="D:"+File.separator+"hello.txt"; File f=new File(fileName); try{ f.createNewFile(); }catch (Exception e) { e.printStackTrace(); } } } 你看,沒有多寫多少吧,呵呵。因此建議使用File類中的常量。 刪除一個文件 import java.io.*; class hello{ public static void main(String[] args) { String fileName="D:"+File.separator+"hello.txt"; File f=new File(fileName); if(f.exists()){ f.delete(); }else{ System.out.println("文件不存在"); } } }
建立一個文件夾
import java.io.*; class hello{ public static void main(String[] args) { String fileName="D:"+File.separator+"hello"; File f=new File(fileName); f.mkdir(); } } 【運行結果】:
D盤下多了一個hello文件夾 列出指定目錄的所有文件(包括隱藏文件):
/** * 使用list列出指定目錄的所有文件 * */ import java.io.*; class hello{ public static void main(String[] args) { String fileName="D:"+File.separator; File f=new File(fileName); String[] str=f.list(); for (int i = 0; i < str.length; i++) { System.out.println(str[i]); } } } 【運行結果】: $RECYCLE.BIN 360 360Downloads 360Rec 360SoftMove Config.Msi da Downloads DriversBackup eclipse java web整合開發和項目實戰 Lenovo MSOCache Program Program Files python RECYGLER.{8F92DA15-A229-A4D5-B5CE-5280C8B89C19} System Volume Information Tomcat6 var vod_cache_data (你的運行結果應該和這個不同的,呵呵) 可是使用list返回的是String數組,。並且列出的不是完整路徑,若是想列出完整路徑的話,須要使用listFiles.他返回的是File的數組
列出指定目錄的所有文件(包括隱藏文件):
/** * 使用listFiles列出指定目錄的所有文件 * listFiles輸出的是完整路徑 * */ import java.io.*; class hello{ public static void main(String[] args) { String fileName="D:"+File.separator; File f=new File(fileName); File[] str=f.listFiles(); for (int i = 0; i < str.length; i++) { System.out.println(str[i]); } } } 【運行結果】: D:\$RECYCLE.BIN D:\360 D:\360Downloads D:\360Rec D:\360SoftMove D:\Config.Msi D:\da D:\Downloads D:\DriversBackup D:\eclipse D:\java web整合開發和項目實戰 D:\Lenovo D:\MSOCache D:\Program D:\Program Files D:\python D:\RECYGLER.{8F92DA15-A229-A4D5-B5CE-5280C8B89C19} D:\System Volume Information D:\Tomcat6 D:\var D:\vod_cache_data D:\新建文件夾 經過比較能夠指定,使用listFiles更加方便、 判斷一個指定的路徑是否爲目錄 /** * 使用isDirectory判斷一個指定的路徑是否爲目錄 * */ import java.io.*; class hello{ public static void main(String[] args) { String fileName="D:"+File.separator; File f=new File(fileName); if(f.isDirectory()){ System.out.println("YES"); }else{ System.out.println("NO"); } } } 【運行結果】:YES 搜索指定目錄的所有內容 /** * 列出指定目錄的所有內容 * */ import java.io.*; class hello{ public static void main(String[] args) { String fileName="D:"+File.separator; File f=new File(fileName); print(f); } public static void print(File f){ if(f!=null){ if(f.isDirectory()){ File[] fileArray=f.listFiles(); if(fileArray!=null){ for (int i = 0; i < fileArray.length; i++) { //遞歸調用 print(fileArray[i]); } } } else{ System.out.println(f); } } } } 【運行結果】: D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\framepages\web4welcome_jsp.java D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\help_005fhome_jsp.class D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\help_005fhome_jsp.java D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\home_jsp.class D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\home_jsp.java D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\index_jsp.class D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\index_jsp.java D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\login_jsp.class D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\login_jsp.java D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\modify_005fuser_005finfo_jsp.class D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\modify_005fuser_005finfo_jsp.java D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\register_005fnotify_jsp.class D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\register_005fnotify_jsp.java D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\sign_005fup_jsp.class D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\sign_005fup_jsp.java D:\Tomcat6\work\Catalina\localhost\nevel\org\apache\jsp\transit_jsp.class …… 【使用RandomAccessFile寫入文件】 /** * 使用RandomAccessFile寫入文件 * */ import java.io.*; class hello{ public static void main(String[] args) throws IOException { String fileName="D:"+File.separator+"hello.txt"; File f=new File(fileName); RandomAccessFile demo=new RandomAccessFile(f,"rw"); demo.writeBytes("asdsad"); demo.writeInt(12); demo.writeBoolean(true); demo.writeChar('A'); demo.writeFloat(1.21f); demo.writeDouble(12.123); demo.close(); } } 若是你此時打開hello。txt查看的話,會發現那是亂碼。 字節流 【向文件中寫入字符串】 /** * 字節流 * 向文件中寫入字符串 * */ import java.io.*; class hello{ public static void main(String[] args) throws IOException { String fileName="D:"+File.separator+"hello.txt"; File f=new File(fileName); OutputStream out =new FileOutputStream(f); String str="你好"; byte[] b=str.getBytes(); out.write(b); out.close(); } } 查看hello.txt會看到「你好」

固然也能夠一個字節一個字節的寫。
/** * 字節流 * 向文件中一個字節一個字節的寫入字符串 * */ import java.io.*; class hello{ public static void main(String[] args) throws IOException { String fileName="D:"+File.separator+"hello.txt"; File f=new File(fileName); OutputStream out =new FileOutputStream(f); String str="你好"; byte[] b=str.getBytes(); for (int i = 0; i < b.length; i++) { out.write(b[i]); } out.close(); } } 結果仍是:「你好」 向文件中追加新內容: /** * 字節流 * 向文件中追加新內容: * */ import java.io.*; class hello{ public static void main(String[] args) throws IOException { String fileName="D:"+File.separator+"hello.txt"; File f=new File(fileName); OutputStream out =new FileOutputStream(f,true); String str="Rollen"; //String str="\r\nRollen"; 能夠換行 byte[] b=str.getBytes(); for (int i = 0; i < b.length; i++) { out.write(b[i]); } out.close(); } } 【運行結果】: 你好Rollen 【讀取文件內容】 /** * 字節流 * 讀文件內容 * */ import java.io.*; class hello{ public static void main(String[] args) throws IOException { String fileName="D:"+File.separator+"hello.txt"; File f=new File(fileName); InputStream in=new FileInputStream(f); byte[] b=new byte[1024]; in.read(b); in.close(); System.out.println(new String(b)); } } 【運行結果】 你好Rollen Rollen_
可是這個例子讀取出來會有大量的空格,咱們能夠利用in.read(b);的返回值來設計程序。以下:
/** * 字節流 * 讀文件內容 * */ import java.io.*; class hello{ public static void main(String[] args) throws IOException { String fileName="D:"+File.separator+"hello.txt"; File f=new File(fileName); InputStream in=new FileInputStream(f); byte[] b=new byte[1024]; int len=in.read(b); in.close(); System.out.println("讀入長度爲:"+len); System.out.println(new String(b,0,len)); } } 【運行結果】: 讀入長度爲:18 你好Rollen Rollen 讀者觀察上面的例子能夠看出,咱們預先申請了一個指定大小的空間,可是有時候這個空間可能過小,有時候可能太大,咱們須要準確的大小,這樣節省空間,那麼咱們能夠這樣幹: /** * 字節流 * 讀文件內容,節省空間 * */ import java.io.*; class hello{ public static void main(String[] args) throws IOException { String fileName="D:"+File.separator+"hello.txt"; File f=new File(fileName); InputStream in=new FileInputStream(f); byte[] b=new byte[(int)f.length()]; in.read(b); System.out.println("文件長度爲:"+f.length()); in.close(); System.out.println(new String(b)); } } 文件長度爲:18 你好Rollen Rollen 將上面的例子改成一個一個讀: /** * 字節流 * 讀文件內容,節省空間 * */ import java.io.*; class hello{ public static void main(String[] args) throws IOException { String fileName="D:"+File.separator+"hello.txt"; File f=new File(fileName); InputStream in=new FileInputStream(f); byte[] b=new byte[(int)f.length()]; for (int i = 0; i < b.length; i++) { b[i]=(byte)in.read(); } in.close(); System.out.println(new String(b)); } } 輸出的結果和上面的同樣。 細心的讀者可能會發現,上面的幾個例子都是在知道文件的內容多大,而後才展開的,有時候咱們不知道文件有多大,這種狀況下,咱們須要判斷是否獨到文件的末尾。 /** * 字節流 *讀文件 * */ import java.io.*; class hello{ public static void main(String[] args) throws IOException { String fileName="D:"+File.separator+"hello.txt"; File f=new File(fileName); InputStream in=new FileInputStream(f); byte[] b=new byte[1024]; int count =0; int temp=0; while((temp=in.read())!=(-1)){ b[count++]=(byte)temp; } in.close(); System.out.println(new String(b)); } } 【運行結果】 你好Rollen Rollen_ 提醒一下,當獨到文件末尾的時候會返回-1.正常狀況下是不會返回-1的 字符流 【向文件中寫入數據】 如今咱們使用字符流 /** * 字符流 * 寫入數據 * */ import java.io.*; class hello{ public static void main(String[] args) throws IOException { String fileName="D:"+File.separator+"hello.txt"; File f=new File(fileName); Writer out =new FileWriter(f); String str="hello"; out.write(str); out.close(); } } 當你打開hello。txt的時候,會看到hello 其實這個例子上以前的例子沒什麼區別,只是你能夠直接輸入字符串,而不須要你將字符串轉化爲字節數組。 當你若是想問文件中追加內容的時候,可使用將上面的聲明out的哪一行換爲: Writer out =new FileWriter(f,true); 這樣,當你運行程序的時候,會發現文件內容變爲: hellohello若是想在文件中換行的話,須要使用「\r\n」 好比將str變爲String str="\r\nhello"; 這樣文件追加的str的內容就會換行了。 從文件中讀內容: /** * 字符流 * 從文件中讀出內容 * */ import java.io.*; class hello{ public static void main(String[] args) throws IOException { String fileName="D:"+File.separator+"hello.txt"; File f=new File(fileName); char[] ch=new char[100]; Reader read=new FileReader(f); int count=read.read(ch); read.close(); System.out.println("讀入的長度爲:"+count); System.out.println("內容爲"+new String(ch,0,count)); } } 【運行結果】: 讀入的長度爲:17 內容爲hellohello hello 固然最好採用循環讀取的方式,由於咱們有時候不知道文件到底有多大。 /** * 字符流 * 從文件中讀出內容 * */ import java.io.*; class hello{ public static void main(String[] args) throws IOException { String fileName="D:"+File.separator+"hello.txt"; File f=new File(fileName); char[] ch=new char[100]; Reader read=new FileReader(f); int temp=0; int count=0; while((temp=read.read())!=(-1)){ ch[count++]=(char)temp; } read.close(); System.out.println("內容爲"+new String(ch,0,count)); } } 運行結果: 內容爲hellohello hello 關於字節流和字符流的區別 實際上字節流在操做的時候自己是不會用到緩衝區的,是文件自己的直接操做的,可是字符流在操做的 時候下後是會用到緩衝區的,是經過緩衝區來操做文件的。 讀者能夠試着將上面的字節流和字符流的程序的最後一行關閉文件的代碼註釋掉,而後運行程序看看。
你就會發現使用字節流的話,文件中已經存在內容,可是使用字符流的時候,文件中仍是沒有內容的,這個時候就要刷新緩衝區。 使用字節流好仍是字符流好呢? 答案是字節流。
首先由於硬盤上的全部文件都是以字節的形式進行傳輸或者保存的,包括圖片等內容。可是字符只是在內存中才會造成的,因此在開發中,字節流使用普遍。

文件的複製 其實DOS下就有一個文件複製功能,好比咱們想把d盤下面的hello.txt文件複製到d盤下面的rollen.txt文件中,那麼咱們就可使用下面的命令: copy d:\hello.txt d:\rollen.txt 運行以後你會在d盤中看見hello.txt.,而且兩個文件的內容是同樣的,(這是屁話) 下面咱們使用程序來複制文件吧。 基本思路仍是從一個文件中讀入內容,邊讀邊寫入另外一個文件,就是這麼簡單。 首先編寫下面的代碼:
/** * 文件的複製 * */ import java.io.*; class hello{ public static void main(String[] args) throws IOException { if(args.length!=2){ System.out.println("命令行參數輸入有誤,請檢查"); System.exit(1); } File file1=new File(args[0]); File file2=new File(args[1]); if(!file1.exists()){ System.out.println("被複制的文件不存在"); System.exit(1); } InputStream input=new FileInputStream(file1); OutputStream output=new FileOutputStream(file2); if((input!=null)&&(output!=null)){ int temp=0; while((temp=input.read())!=(-1)){ output.write(temp); } } input.close(); output.close(); } } 而後在命令行下面 javac hello.java java hello d:\hello.txt d:\rollen.txt 如今你就會在d盤看到rollen。txt了, OutputStreramWriter 和InputStreamReader類 整個IO類中除了字節流和字符流還包括字節和字符轉換流。 OutputStreramWriter將輸出的字符流轉化爲字節流 InputStreamReader將輸入的字節流轉換爲字符流 可是無論如何操做,最後都是以字節的形式保存在文件中的。 將字節輸出流轉化爲字符輸出流 /** * 將字節輸出流轉化爲字符輸出流 * */ import java.io.*; class hello{ public static void main(String[] args) throws IOException { String fileName= "d:"+File.separator+"hello.txt"; File file=new File(fileName); Writer out=new OutputStreamWriter(new FileOutputStream(file)); out.write("hello"); out.close(); } } 運行結果:文件中內容爲:hello
將字節輸入流變爲字符輸入流
/** * 將字節輸入流變爲字符輸入流 * */ import java.io.*; class hello{ public static void main(String[] args) throws IOException { String fileName= "d:"+File.separator+"hello.txt"; File file=new File(fileName); Reader read=new InputStreamReader(new FileInputStream(file)); char[] b=new char[100]; int len=read.read(b); System.out.println(new String(b,0,len)); read.close(); } } 【運行結果】:hello
前面列舉的輸出輸入都是以文件進行的,如今咱們之內容爲輸出輸入目的地,使用內存操做流 ByteArrayInputStream 主要將內容寫入內容 ByteArrayOutputStream 主要將內容從內存輸出
使用內存操做流將一個大寫字母轉化爲小寫字母
/** * 使用內存操做流將一個大寫字母轉化爲小寫字母 * */ import java.io.*; class hello{ public static void main(String[] args) throws IOException { String str="ROLLENHOLT"; ByteArrayInputStream input=new ByteArrayInputStream(str.getBytes()); ByteArrayOutputStream output=new ByteArrayOutputStream(); int temp=0; while((temp=input.read())!=-1){ char ch=(char)temp; output.write(Character.toLowerCase(ch)); } String outStr=output.toString(); input.close(); output.close(); System.out.println(outStr); } } 【運行結果】: rollenholt
內容操做流通常使用來生成一些臨時信息採用的,這樣能夠避免刪除的麻煩。
管道流 管道流主要能夠進行兩個線程之間的通訊。 PipedOutputStream 管道輸出流 PipedInputStream 管道輸入流 驗證管道流
/** * 驗證管道流 * */ import java.io.*; /** * 消息發送類 * */ class Send implements Runnable{ private PipedOutputStream out=null; public Send() { out=new PipedOutputStream(); } public PipedOutputStream getOut(){ return this.out; } public void run(){ String message="hello , Rollen"; try{ out.write(message.getBytes()); }catch (Exception e) { e.printStackTrace(); }try{ out.close(); }catch (Exception e) { e.printStackTrace(); } } } /** * 接受消息類 * */ class Recive implements Runnable{ private PipedInputStream input=null; public Recive(){ this.input=new PipedInputStream(); } public PipedInputStream getInput(){ return this.input; } public void run(){ byte[] b=new byte[1000]; int len=0; try{ len=this.input.read(b); }catch (Exception e) { e.printStackTrace(); }try{ input.close(); }catch (Exception e) { e.printStackTrace(); } System.out.println("接受的內容爲 "+(new String(b,0,len))); } } /** * 測試類 * */ class hello{ public static void main(String[] args) throws IOException { Send send=new Send(); Recive recive=new Recive(); try{ //管道鏈接 send.getOut().connect(recive.getInput()); }catch (Exception e) { e.printStackTrace(); } new Thread(send).start(); new Thread(recive).start(); } } 【運行結果】: 接受的內容爲 hello , Rollen

打印流
/** * 使用PrintStream進行輸出 * */ import java.io.*; class hello { public static void main(String[] args) throws IOException { PrintStream print = new PrintStream(new FileOutputStream(new File("d:" + File.separator + "hello.txt"))); print.println(true); print.println("Rollen"); print.close(); } } 【運行結果】: true Rollen

固然也能夠格式化輸出
/** * 使用PrintStream進行輸出 * 並進行格式化 * */ import java.io.*; class hello { public static void main(String[] args) throws IOException { PrintStream print = new PrintStream(new FileOutputStream(new File("d:" + File.separator + "hello.txt"))); String name="Rollen"; int age=20; print.printf("姓名:%s. 年齡:%d.",name,age); print.close(); } } 【運行結果】: 姓名:Rollen. 年齡:20. 使用OutputStream向屏幕上輸出內容 /** * 使用OutputStream向屏幕上輸出內容 * */ import java.io.*; class hello { public static void main(String[] args) throws IOException { OutputStream out=System.out; try{ out.write("hello".getBytes()); }catch (Exception e) { e.printStackTrace(); } try{ out.close(); }catch (Exception e) { e.printStackTrace(); } } } 【運行結果】: hello 輸入輸出重定向 import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; /** * 爲System.out.println()重定向輸出 * */ public class systemDemo{ public static void main(String[] args){ // 此刻直接輸出到屏幕 System.out.println("hello"); File file = new File("d:" + File.separator + "hello.txt"); try{ System.setOut(new PrintStream(new FileOutputStream(file))); }catch(FileNotFoundException e){ e.printStackTrace(); } System.out.println("這些內容在文件中才能看到哦!"); } } 【運行結果】: eclipse的控制檯輸出的是hello。而後當咱們查看d盤下面的hello.txt文件的時候,會在裏面看到:這些內容在文件中才能看到哦!
import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; /** * System.err重定向 這個例子也提示咱們可使用這種方法保存錯誤信息 * */ public class systemErr{ public static void main(String[] args){ File file = new File("d:" + File.separator + "hello.txt"); System.err.println("這些在控制檯輸出"); try{ System.setErr(new PrintStream(new FileOutputStream(file))); }catch(FileNotFoundException e){ e.printStackTrace(); } System.err.println("這些在文件中才能看到哦!"); } } 【運行結果】: 你會在eclipse的控制檯看到紅色的輸出:「這些在控制檯輸出」,而後在d盤下面的hello.txt中會看到:這些在文件中才能看到哦!
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; /** * System.in重定向 * */ public class systemIn{ public static void main(String[] args){ File file = new File("d:" + File.separator + "hello.txt"); if(!file.exists()){ return; }else{ try{ System.setIn(new FileInputStream(file)); }catch(FileNotFoundException e){ e.printStackTrace(); } byte[] bytes = new byte[1024]; int len = 0; try{ len = System.in.read(bytes); }catch(IOException e){ e.printStackTrace(); } System.out.println("讀入的內容爲:" + new String(bytes, 0, len)); } } } 【運行結果】: 前提是個人d盤下面的hello.txt中的內容是:「這些文件中的內容哦!」,而後運行程序,輸出的結果爲:讀入的內容爲:這些文件中的內容哦! BufferedReader的小例子 注意: BufferedReader只能接受字符流的緩衝區,由於每個中文須要佔據兩個字節,因此須要將System.in這個字節輸入流變爲字符輸入流,採用: BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); 下面給一個實例: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * 使用緩衝區從鍵盤上讀入內容 * */ public class BufferedReaderDemo{ public static void main(String[] args){ BufferedReader buf = new BufferedReader( new InputStreamReader(System.in)); String str = null; System.out.println("請輸入內容"); try{ str = buf.readLine(); }catch(IOException e){ e.printStackTrace(); } System.out.println("你輸入的內容是:" + str); } } 運行結果: 請輸入內容 dasdas 你輸入的內容是:dasdas Scanner類 其實咱們比較經常使用的是採用Scanner類來進行數據輸入,下面來給一個Scanner的例子吧 import java.util.Scanner; /** * Scanner的小例子,從鍵盤讀數據 * */ public class ScannerDemo{ public static void main(String[] args){ Scanner sca = new Scanner(System.in); // 讀一個整數 int temp = sca.nextInt(); System.out.println(temp); //讀取浮點數 float flo=sca.nextFloat(); System.out.println(flo); //讀取字符 //...等等的,都是一些太基礎的,就不師範了。 } } 其實Scanner能夠接受任何的輸入流
下面給一個使用Scanner類從文件中讀出內容
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; /** * Scanner的小例子,從文件中讀內容 * */ public class ScannerDemo{ public static void main(String[] args){ File file = new File("d:" + File.separator + "hello.txt"); Scanner sca = null; try{ sca = new Scanner(file); }catch(FileNotFoundException e){ e.printStackTrace(); } String str = sca.next(); System.out.println("從文件中讀取的內容是:" + str); } } 【運行結果】: 從文件中讀取的內容是:這些文件中的內容哦!

數據操做流DataOutputStream、DataInputStream類
import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class DataOutputStreamDemo{ public static void main(String[] args) throws IOException{ File file = new File("d:" + File.separator + "hello.txt"); char[] ch = { 'A', 'B', 'C' }; DataOutputStream out = null; out = new DataOutputStream(new FileOutputStream(file)); for(char temp : ch){ out.writeChar(temp); } out.close(); } } A B C
如今咱們在上面例子的基礎上,使用DataInputStream讀出內容
import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class DataOutputStreamDemo{ public static void main(String[] args) throws IOException{ File file = new File("d:" + File.separator + "hello.txt"); DataInputStream input = new DataInputStream(new FileInputStream(file)); char[] ch = new char[10]; int count = 0; char temp; while((temp = input.readChar()) != 'C'){ ch[count++] = temp; } System.out.println(ch); } } 【運行結果】: AB
合併流 SequenceInputStream SequenceInputStream主要用來將2個流合併在一塊兒,好比將兩個txt中的內容合併爲另一個txt。下面給出一個實例:
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.SequenceInputStream; /** * 將兩個文本文件合併爲另一個文本文件 * */ public class SequenceInputStreamDemo{ public static void main(String[] args) throws IOException{ File file1 = new File("d:" + File.separator + "hello1.txt"); File file2 = new File("d:" + File.separator + "hello2.txt"); File file3 = new File("d:" + File.separator + "hello.txt"); InputStream input1 = new FileInputStream(file1); InputStream input2 = new FileInputStream(file2); OutputStream output = new FileOutputStream(file3); // 合併流 SequenceInputStream sis = new SequenceInputStream(input1, input2); int temp = 0; while((temp = sis.read()) != -1){ output.write(temp); } input1.close(); input2.close(); output.close(); sis.close(); } } 【運行結果】 結果會在hello.txt文件中包含hello1.txt和hello2.txt文件中的內容。
文件壓縮 ZipOutputStream類 先舉一個壓縮單個文件的例子吧:
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipOutputStreamDemo1{ public static void main(String[] args) throws IOException{ File file = new File("d:" + File.separator + "hello.txt"); File zipFile = new File("d:" + File.separator + "hello.zip"); InputStream input = new FileInputStream(file); ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream( zipFile)); zipOut.putNextEntry(new ZipEntry(file.getName())); // 設置註釋 zipOut.setComment("hello"); int temp = 0; while((temp = input.read()) != -1){ zipOut.write(temp); } input.close(); zipOut.close(); } } 【運行結果】 運行結果以前,我建立了一個hello.txt的文件,本來大小56個字節,可是壓縮以後產生hello.zip以後,竟然變成了175個字節,有點搞不懂。 不過結果確定是正確的,我只是提出個人一個疑問而已。 上面的這個例子測試的是壓縮單個文件,下面的們來看看如何壓縮多個文件。 import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * 一次性壓縮多個文件 * */ public class ZipOutputStreamDemo2{ public static void main(String[] args) throws IOException{ // 要被壓縮的文件夾 File file = new File("d:" + File.separator + "temp"); File zipFile = new File("d:" + File.separator + "zipFile.zip"); InputStream input = null; ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream( zipFile)); zipOut.setComment("hello"); if(file.isDirectory()){ File[] files = file.listFiles(); for(int i = 0; i < files.length; ++i){ input = new FileInputStream(files[i]); zipOut.putNextEntry(new ZipEntry(file.getName() + File.separator + files[i].getName())); int temp = 0; while((temp = input.read()) != -1){ zipOut.write(temp); } input.close(); } } zipOut.close(); } } 【運行結果】 先看看要被壓縮的文件吧: 接下來看看壓縮以後的: 你們天然想到,既然能壓縮,天然能解壓縮,在談解壓縮以前,咱們會用到一個ZipFile類,先給一個這個例子吧。java中的每個壓縮文件都是可使用ZipFile來進行表示的 import java.io.File; import java.io.IOException; import java.util.zip.ZipFile; /** * ZipFile演示 * */ public class ZipFileDemo{ public static void main(String[] args) throws IOException{ File file = new File("d:" + File.separator + "hello.zip"); ZipFile zipFile = new ZipFile(file); System.out.println("壓縮文件的名稱爲:" + zipFile.getName()); } } 【運行結果】: 壓縮文件的名稱爲:d:\hello.zip 如今咱們呢是時候來看看如何加壓縮文件了,和以前同樣,先讓咱們來解壓單個壓縮文件(也就是壓縮文件中只有一個文件的狀況),咱們採用前面的例子產生的壓縮文件hello.zip import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * 解壓縮文件(壓縮文件中只有一個文件的狀況) * */ public class ZipFileDemo2{ public static void main(String[] args) throws IOException{ File file = new File("d:" + File.separator + "hello.zip"); File outFile = new File("d:" + File.separator + "unZipFile.txt"); ZipFile zipFile = new ZipFile(file); ZipEntry entry = zipFile.getEntry("hello.txt"); InputStream input = zipFile.getInputStream(entry); OutputStream output = new FileOutputStream(outFile); int temp = 0; while((temp = input.read()) != -1){ output.write(temp); } input.close(); output.close(); } } 【運行結果】: 解壓縮以前:          這個壓縮文件仍是175字節 解壓以後產生:         又回到了56字節,表示鬱悶。 如今讓咱們來解壓一個壓縮文件中包含多個文件的狀況吧 ZipInputStream類 當咱們須要解壓縮多個文件的時候,ZipEntry就沒法使用了,若是想操做更加複雜的壓縮文件,咱們就必須使用ZipInputStream類
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; /** * 解壓縮一個壓縮文件中包含多個文件的狀況 * */ public class ZipFileDemo3{ public static void main(String[] args) throws IOException{ File file = new File("d:" + File.separator + "zipFile.zip"); File outFile = null; ZipFile zipFile = new ZipFile(file); ZipInputStream zipInput = new ZipInputStream(new FileInputStream(file)); ZipEntry entry = null; InputStream input = null; OutputStream output = null; while((entry = zipInput.getNextEntry()) != null){ System.out.println("解壓縮" + entry.getName() + "文件"); outFile = new File("d:" + File.separator + entry.getName()); if(!outFile.getParentFile().exists()){ outFile.getParentFile().mkdir(); } if(!outFile.exists()){ outFile.createNewFile(); } input = zipFile.getInputStream(entry); output = new FileOutputStream(outFile); int temp = 0; while((temp = input.read()) != -1){ output.write(temp); } input.close(); output.close(); } } } 【運行結果】: 被解壓的文件: 解壓以後再D盤下會出現一個temp文件夾,裏面內容: PushBackInputStream回退流 import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.PushbackInputStream; /** * 回退流操做 * */ public class PushBackInputStreamDemo{ public static void main(String[] args) throws IOException{ String str = "hello,rollenholt"; PushbackInputStream push = null; ByteArrayInputStream bat = null; bat = new ByteArrayInputStream(str.getBytes()); push = new PushbackInputStream(bat); int temp = 0; while((temp = push.read()) != -1){ if(temp == ','){ push.unread(temp); temp = push.read(); System.out.print("(回退" + (char) temp + ") "); }else{ System.out.print((char) temp); } } } } 【運行結果】: hello(回退,) rollenholt /** * 取得本地的默認編碼 * */ public class CharSetDemo{ public static void main(String[] args){ System.out.println("系統默認編碼爲:" + System.getProperty("file.encoding")); } } 【運行結果】: 系統默認編碼爲:GBK 亂碼的產生: import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; /** * 亂碼的產生 * */ public class CharSetDemo2{ public static void main(String[] args) throws IOException{ File file = new File("d:" + File.separator + "hello.txt"); OutputStream out = new FileOutputStream(file); byte[] bytes = "你好".getBytes("ISO8859-1"); out.write(bytes); out.close(); } } 【運行結果】: ?? 通常狀況下產生亂碼,都是因爲編碼不一致的問題。 對象的序列化 對象序列化就是把一個對象變爲二進制數據流的一種方法。 一個類要想被序列化,就行必須實現java.io.Serializable接口。雖然這個接口中沒有任何方法,就如同以前的cloneable接口同樣。實現了這個接口以後,就表示這個類具備被序列化的能力。 先讓咱們實現一個具備序列化能力的類吧: import java.io.*; /** * 實現具備序列化能力的類 * */ public class SerializableDemo implements Serializable{ public SerializableDemo(){ } public SerializableDemo(String name, int age){ this.name=name; this.age=age; } @Override public String toString(){ return "姓名:"+name+" 年齡:"+age; } private String name; private int age; } 這個類就具備實現序列化能力, 在繼續將序列化以前,先將一下ObjectInputStream和ObjectOutputStream這兩個類
先給一個ObjectOutputStream的例子吧:
import java.io.Serializable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; /** * 實現具備序列化能力的類 * */ public class Person implements Serializable{ public Person(){ } public Person(String name, int age){ this.name = name; this.age = age; } @Override public String toString(){ return "姓名:" + name + " 年齡:" + age; } private String name; private int age; } /** * 示範ObjectOutputStream * */ public class ObjectOutputStreamDemo{ public static void main(String[] args) throws IOException{ File file = new File("d:" + File.separator + "hello.txt"); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream( file)); oos.writeObject(new Person("rollen", 20)); oos.close(); } } 【運行結果】: 當咱們查看產生的hello.txt的時候,看到的是亂碼,呵呵。由於是二進制文件。
雖然咱們不能直接查看裏面的內容,可是咱們可使用ObjectInputStream類查看:
import java.io.File; import java.io.FileInputStream; import java.io.ObjectInputStream; /** * ObjectInputStream示範 * */ public class ObjectInputStreamDemo{ public static void main(String[] args) throws Exception{ File file = new File("d:" + File.separator + "hello.txt"); ObjectInputStream input = new ObjectInputStream(new FileInputStream( file)); Object obj = input.readObject(); input.close(); System.out.println(obj); } } 【運行結果】 姓名:rollen 年齡:20 到底序列化什麼內容呢? 其實只有屬性會被序列化。 Externalizable接口 被Serializable接口聲明的類的對象的屬性都將被序列化,可是若是想自定義序列化的內容的時候,就須要實現Externalizable接口。 當一個類要使用Externalizable這個接口的時候,這個類中必需要有一個無參的構造函數,若是沒有的話,在構造的時候會產生異常,這是由於在反序列話的時候會默認調用無參的構造函數。
如今咱們來演示一下序列化和反序列話:
package IO; import java.io.Externalizable; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; /** * 序列化和反序列化的操做 * */ public class ExternalizableDemo{ public static void main(String[] args) throws Exception{ ser(); // 序列化 dser(); // 反序列話 } public static void ser() throws Exception{ File file = new File("d:" + File.separator + "hello.txt"); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream( file)); out.writeObject(new Person("rollen", 20)); out.close(); } public static void dser() throws Exception{ File file = new File("d:" + File.separator + "hello.txt"); ObjectInputStream input = new ObjectInputStream(new FileInputStream( file)); Object obj = input.readObject(); input.close(); System.out.println(obj); } } class Person implements Externalizable{ public Person(){ } public Person(String name, int age){ this.name = name; this.age = age; } @Override public String toString(){ return "姓名:" + name + " 年齡:" + age; } // 複寫這個方法,根據須要能夠保存的屬性或者具體內容,在序列化的時候使用 @Override public void writeExternal(ObjectOutput out) throws IOException{ out.writeObject(this.name); out.writeInt(age); } // 複寫這個方法,根據須要讀取內容 反序列話的時候須要 @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException{ this.name = (String) in.readObject(); this.age = in.readInt(); } private String name; private int age; } 【運行結果】: 姓名:rollen 年齡:20
本例中,咱們將所有的屬性都保留了下來, Serializable接口實現的操做實際上是吧一個對象中的所有屬性進行序列化,固然也可使用咱們上使用是Externalizable接口以實現部分屬性的序列化,可是這樣的操做比較麻煩, 當咱們使用Serializable接口實現序列化操做的時候,若是一個對象的某一個屬性不想被序列化保存下來,那麼咱們可使用transient關鍵字進行說明: 下面舉一個例子:
package IO; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; /** * 序列化和反序列化的操做 * */ public class serDemo{ public static void main(String[] args) throws Exception{ ser(); // 序列化 dser(); // 反序列話 } public static void ser() throws Exception{ File file = new File("d:" + File.separator + "hello.txt"); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream( file)); out.writeObject(new Person1("rollen", 20)); out.close(); } public static void dser() throws Exception{ File file = new File("d:" + File.separator + "hello.txt"); ObjectInputStream input = new ObjectInputStream(new FileInputStream( file)); Object obj = input.readObject(); input.close(); System.out.println(obj); } } class Person1 implements Serializable{ public Person1(){ } public Person1(String name, int age){ this.name = name; this.age = age; } @Override public String toString(){ return "姓名:" + name + " 年齡:" + age; } // 注意這裏 private transient String name; private int age; } 【運行結果】: 姓名:null 年齡:20
最後在給一個序列化一組對象的例子吧:
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; /** * 序列化一組對象 * */ public class SerDemo1{ public static void main(String[] args) throws Exception{ Student[] stu = { new Student("hello", 20), new Student("world", 30), new Student("rollen", 40) }; ser(stu); Object[] obj = dser(); for(int i = 0; i < obj.length; ++i){ Student s = (Student) obj[i]; System.out.println(s); } } // 序列化 public static void ser(Object[] obj) throws Exception{ File file = new File("d:" + File.separator + "hello.txt"); ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream( file)); out.writeObject(obj); out.close(); } // 反序列化 public static Object[] dser() throws Exception{ File file = new File("d:" + File.separator + "hello.txt"); ObjectInputStream input = new ObjectInputStream(new FileInputStream( file)); Object[] obj = (Object[]) input.readObject(); input.close(); return obj; } } class Student implements Serializable{ public Student(){ } public Student(String name, int age){ this.name = name; this.age = age; } @Override public String toString(){ return "姓名: " + name + " 年齡:" + age; } private String name; private int age; } 【運行結果】: 姓名: hello 年齡:20 姓名: world 年齡:30 姓名: rollen 年齡:40
相關文章
相關標籤/搜索