1. 程式人生 > 其它 >Java之IO流補充

Java之IO流補充

IO流例子

package com.hanqi.maya.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;

public class Test3 {
    public static void main(String[] args) {
        File file=new File("E:\ceshi.txt");
        File ofile=new File("E:\cewshi8.txt");
        
        Reader r=null;
        
        try {
            r=new FileReader(file);
            Writer w=new FileWriter(ofile,true);//true表示追加,不加則原本表示替換
            BufferedReader br=new BufferedReader(r);
            BufferedWriter bw=new BufferedWriter(w);
            String s=null;
            while((s=br.readLine())!=null){
                System.out.print(s);
                bw.write(s);
                bw.flush();//一個好的程式設計習慣應該在此處使用flush,寫入需要用 flush 重新整理流,否則會在緩衝區不寫入檔案
            }
            br.close();
            bw.close();//呼叫該方法前會自動呼叫 flush 
        } catch (FileNotFoundException e) {
            
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

檔案流(位元組流, 字元流)

位元組流例子

 1 //位元組輸入流
 2 //讀取內容並輸出讀取多少位元組
 3 package com.zijie;
 4 
 5 import java.io.FileInputStream;
 6 import java.io.FileNotFoundException;
 7 import java.io.IOException;
 8 
 9 public class TestFileInputStream
10 {
11     public static void main(String[] args) {
12         int b = 0;
13 
14         FileInputStream in = null;
15         try{
16             in = new FileInputStream("E:\Java\0801 流後傳 執行緒\執行緒.txt");
17         } catch(FileNotFoundException e) {
18             System.out.println("找不到指定的檔案");
19             System.exit(-1);
20         }
21 
22         try{
23             long num = 0;
24             // 返回-1的話就表示已經讀到了檔案的結尾
25             while((b = in.read()) != -1) {
26                 System.out.print((char)b);
27                 num++;
28             }
29             in.close();
30             System.out.println("nn共讀取了" + num + "個位元組");
31         } catch(IOException e1) {
32             System.out.println("讀取檔案時出現異常");
33             System.exit(-1);
34         }
35     }
36 }
 1 //位元組輸出流
 2 //複製檔案
 3 package com.zijie;
 4 
 5 import java.io.FileInputStream;
 6 import java.io.FileNotFoundException;
 7 import java.io.FileOutputStream;
 8 import java.io.IOException;
 9 
10 public class TestFileOutputStream {
11     public static void main(String[] args) {
12         int b = 0;
13         FileInputStream in = null;
14         FileOutputStream out = null;
15         try {
16             in = new FileInputStream("E:\Java\0801 流後傳 執行緒\執行緒.txt");
17             // OutputStream有這個檔案就往這個檔案裡面寫, 沒有的話就自動建立一個
18             out = new FileOutputStream("E:\Java\0801 流後傳 執行緒\執行緒-ceshi.txt");
19             // 一邊讀, 一邊寫
20             while ((b = in.read()) != -1) {
21                 out.write(b);
22             }
23         } catch (FileNotFoundException e) {
24             System.out.println("找不到指定檔案");
25             System.exit(-1);
26         } catch (IOException e) {
27             System.out.println("檔案複製出錯");
28             System.exit(-1);
29         }
30         System.out.println("檔案成功複製");
31     }
32 }

字元流例子

 1 //字元輸入流
 2 //讀取檔案內容
 3 package com.zifu;
 4 
 5 import java.io.FileNotFoundException;
 6 import java.io.FileReader;
 7 import java.io.IOException;
 8 
 9 public class TestFileReader {
10     public static void main(String[] args) {
11         FileReader fr = null;
12         int c = 0;
13         try {
14             fr = new FileReader("E:\Java\0801 流後傳 執行緒\執行緒.txt");
15             while ((c = fr.read()) != -1) {
16                 System.out.print((char) c);
17             }
18             fr.close();
19         } catch (FileNotFoundException e) {
20             System.out.println("檔案未找到");
21             System.exit(-1);
22         } catch (IOException e) {
23             System.out.println("讀取檔案時出現異常");
24             System.exit(-1);
25         }
26     }
27 }
 1 //字元輸入流
 2 //不斷寫入int型,寫入為ASCII表
 3 package com.zifu;
 4 
 5 import java.io.FileWriter;
 6 import java.io.IOException;
 7 
 8 public class TestFileWriter {
 9     public static void main(String[] args) {
10         FileWriter fw = null;
11         try {
12             fw = new FileWriter("E:\Java\0801 流後傳 執行緒\執行緒-ceshi1.txt");
13             for (int i = 1; i <= 50000; i++) {
14                     fw.write(i);
15             }
16         } catch (IOException e) {
17             System.out.println("寫入檔案出錯 !");
18             System.exit(-1);
19         }
20     }
21 }

緩衝流

 1 package com.buffer;
 2 
 3 import java.io.BufferedInputStream;
 4 import java.io.FileInputStream;
 5 import java.io.FileNotFoundException;
 6 import java.io.IOException;
 7 
 8 public class TestBufferStream {
 9     public static void main(String[] args) {
10 
11         byte[] bb = new byte[50];
12         try {
13             FileInputStream fis = new FileInputStream("E:\Java\0801 流後傳 執行緒\ceshi.txt");
14             BufferedInputStream bis = new BufferedInputStream(fis);//將檔案位元組流,轉換成帶緩衝的輸入位元組流
15             int c = 0;
16             System.out.println((char)bis.read());
17             System.out.println((char)bis.read());
18 /*            while((c = bis.read()) != -1) {
19                 System.out.print((char)c+", ");
20             }*/
21             // 標記到第30的位置再開始讀資料
22             bis.mark(100);//見的總承包 mark的方法 InputStream
23             
24             for (int i = 0; i <= 10 && (c = bis.read()) != -1; i++) {
25                 System.out.print((char)c);
26             }
27             System.out.println();
28             // 回到mark標記的那個地方
29             bis.reset();//見的總承包reset的方法InputStream 。 
30             for (int i = 0; i <= 10 && (c = bis.read()) != -1; i++) {
31                 System.out.print((char)c);
32             }
33             bis.close();
34         } catch (FileNotFoundException e) {
35             e.printStackTrace();
36         } catch (IOException e) {
37             e.printStackTrace();
38         }
39         
40     }
41 }
 1 package com.buffer;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.BufferedWriter;
 5 import java.io.FileNotFoundException;
 6 import java.io.FileReader;
 7 import java.io.FileWriter;
 8 import java.io.IOException;
 9 
10 public class TestBufferRW {
11     public static void main(String[] args) {
12         
13         try {
14             BufferedWriter bw = new BufferedWriter(new FileWriter("E:\Java\0801 流後傳 執行緒\ceshi.txt"));
15             BufferedReader br = new BufferedReader(new FileReader("E:\Java\0801 流後傳 執行緒\ceshi.txt"));
16             
17             String s = null;
18             
19             for (int i = 0; i < 100; i++) {
20                 s = "" + Math.random();
21                 //bw.write(s);
22                 bw.append(s);//寫入檔案
23                 bw.newLine();
24             }
25             
26             bw.flush();
27             // 特別好用的方法, readLine
28             while((s = br.readLine()) != null) {//獲取檔案內容輸出到控制檯
29                 System.out.println(s);
30             }
31             br.close();
32             bw.close();
33         } catch (FileNotFoundException e) {
34             e.printStackTrace();
35         } catch (IOException e) {
36             e.printStackTrace();
37         }
38     }
39 }

轉換流  convert--->位元組-字元

列印當前系統的字元編碼:

System.out.println(osw.getEncoding());

 1 package com.convert;
 2 
 3 import java.io.FileNotFoundException;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 import java.io.OutputStreamWriter;
 7 import java.io.UnsupportedEncodingException;
 8 
 9 public class TestTranForm1 {
10     public static void main(String[] args) {
11         OutputStreamWriter osw = null;
12         try {
13             
14             osw = new OutputStreamWriter(new FileOutputStream("E:\Java\0801 流後傳 執行緒\ceshi.txt"));
15             osw.write("山東淄博");//寫入檔案
16             // 預設使用當前系統的字元編碼
17             System.out.println(osw.getEncoding());
18             osw.close();
19             
20             // FileOutputStream加第二個引數true表示追加內容
21             osw = new OutputStreamWriter(new FileOutputStream("E:\Java\0801 流後傳 執行緒\ceshi.txt", true), "utf-8");//更改字元編碼
22             osw.write("qwerttttt");
23             System.out.println(osw.getEncoding());
24             osw.close();
25             
26         } catch (FileNotFoundException e) {
27             e.printStackTrace();
28         } catch (UnsupportedEncodingException e) { 
29             e.printStackTrace();
30         } catch (IOException e) {
31             e.printStackTrace();
32         }
33         
34     }
35 }

阻塞式方法

獲取輸入的內容轉換成大寫,如果輸入的 exit 退出

 1 package com.convert;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.IOException;
 5 import java.io.InputStreamReader;
 6 
 7 public class TestTranForm2 {
 8     public static void main(String[] args) {
 9         try {
10             InputStreamReader isr = new InputStreamReader(System.in);//包一層字元流
11             BufferedReader br = new BufferedReader(isr);//在包一層緩衝字元流
12             String s = null;
13             
14             s = br.readLine();//從字元流讀取一行,你寫入的內容
15             
16             while(s != null) {
17                 if(s.equalsIgnoreCase("exit")) {//忽略大小寫的相同
18                     break;
19                 }
20                 System.out.println(s.toUpperCase());//將字串轉換成大寫在控制檯輸出
21                 s = br.readLine();//再次獲取輸入的內容
22             }
23             
24             br.close();
25             
26             // 阻塞式方法(同步方法---不輸入就不能幹別的)
27         } catch (IOException e) {
28             e.printStackTrace();
29         }
30     }
31 }

資料流--->八大資料型別

 1 package com.data;
 2 
 3 import java.io.ByteArrayInputStream;
 4 import java.io.ByteArrayOutputStream;
 5 import java.io.DataInputStream;
 6 import java.io.DataOutputStream;
 7 import java.io.IOException;
 8 
 9 public class TestDataStream {
10     public static void main(String[] args) {
11         ByteArrayOutputStream baos = new ByteArrayOutputStream();//位元組陣列輸出流
12         DataOutputStream dos = new DataOutputStream(baos);//資料處理流,這個流可以直接寫入基礎資料型別
13         try {
14             dos.writeDouble(Math.random());
15             dos.writeBoolean(true);
16             ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());//將輸出流轉換為位元組陣列
17             System.out.println(bais.available());//裡面包含的所有資料的長度
18             DataInputStream dis = new DataInputStream(bais);
19             /*
20              * 先進先出---佇列
21              * 先進後出---棧
22              */
23             System.out.println(dis.readDouble());//資料流可以直接讀取基本資料型別
24             System.out.println(dis.readBoolean());
25             dos.close();
26             dis.close();
27         } catch (IOException e) {
28             // TODO Auto-generated catch block
29             e.printStackTrace();
30         }
31     }
32 }

print流  列印流--->System.out.println();

 1 package com.print;
 2 
 3 import java.io.FileNotFoundException;
 4 import java.io.FileOutputStream;
 5 import java.io.PrintStream;
 6 
 7 public class TestPrintStream1 {
 8     public static void main(String[] args) {
 9         PrintStream ps = null;//列印流
10         
11         try {
12             FileOutputStream fos = new FileOutputStream("e:\go\testprint.txt");//檔案位元組輸出流
13             ps = new PrintStream(fos);
14         } catch (FileNotFoundException e) {
15             e.printStackTrace();
16         }
17         
18         if(ps != null) {
19             // 設定預設的輸出物件
20             System.setOut(ps);
21         }
22         
23         for(char c = 0;c<=60000;c++) {//輸出6萬個字元
24             System.out.print(c);
25             if(c % 100 == 0) {//輸出到檔案,不是控制檯
26                 System.out.println();
27             }
28         }
29     }
30 }

定義方法,讀取並列印檔案

 1 package com.print;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.FileNotFoundException;
 5 import java.io.FileReader;
 6 import java.io.IOException;
 7 import java.io.PrintStream;
 8 
 9 public class TestPrintStream2 {
10     public static void main(String[] args) {
11         String fileName = "e:\go\file.txt";
12         
13         list(fileName, System.out);
14     }
15 
16     private static void list(String fileName, PrintStream ps) {
17         try {
18             BufferedReader br = new BufferedReader(new FileReader(fileName));//讀取檔案
19             String s = null;
20             
21             while((s = br.readLine()) != null) {
22                 ps.println(s);//讀取並列印
23             }
24             br.close();
25         } catch (FileNotFoundException e) {
26             e.printStackTrace();
27         } catch (IOException e) {
28             ps.println("無法讀取檔案 !");
29             e.printStackTrace();
30         }
31     }
32 }

模擬日誌效果

輸入內容,列印,並用分割線分開,最後列印當前日期

 1 package com.print;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.FileWriter;
 5 import java.io.IOException;
 6 import java.io.InputStreamReader;
 7 import java.io.PrintWriter;
 8 import java.util.Date;
 9 
10 public class TestPrintStream3 {
11 
12     public static void main(String[] args) {
13         String s = null;
14         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));//位元組流轉換字元流
15         
16         PrintWriter pwLog;
17         try {
18             FileWriter fw = new FileWriter("e:\Java\Ceshi-stream.log", true);//輸出流的位置追加內容
19             pwLog = new PrintWriter(fw);
20             while((s = br.readLine()) != null) {//獲取輸入
21                 if(s.equalsIgnoreCase("exit")) {
22                     break;
23                 }
24                 System.out.println(s.toUpperCase());//列印到控制檯大寫
25                 pwLog.println("---------------------");//列印到檔案分割線
26                 pwLog.println(s.toUpperCase());//列印到檔案大寫
27                 pwLog.flush();
28             }
29             pwLog.println("========== " + new Date() + " ===================");//結束後列印當前日期
30             pwLog.flush();
31             pwLog.close();
32         } catch (IOException e) {
33             e.printStackTrace();
34         }
35         
36         
37     }
38 
39 }

Object流

 1 package com.object;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileNotFoundException;
 5 import java.io.FileOutputStream;
 6 import java.io.IOException;
 7 import java.io.ObjectInputStream;
 8 import java.io.ObjectOutputStream;
 9 import java.io.Serializable;
10 
11 public class TestObjectStream {
12     public static void main(String[] args) {
13         try {
14             Test t = new Test();//例項化,自定義的類
15             t.i += 5;
16             FileOutputStream fos = new FileOutputStream("E:\Java\0801 流後傳 執行緒\ceshi.txt");//定義輸出位置
17             ObjectOutputStream oos = new ObjectOutputStream(fos);//物件處理流包起來
18             oos.writeObject(t);//將物件寫入到檔案
19             oos.flush();
20             oos.close();
21             
22             FileInputStream fis = new FileInputStream("E:\Java\0801 流後傳 執行緒\ceshi.txt");//將檔案讀出來
23             ObjectInputStream ois = new ObjectInputStream(fis);
24             Test tread = (Test)ois.readObject();
25             System.out.println(tread);
26             ois.close();
27         } catch (FileNotFoundException e) {
28             e.printStackTrace();
29         } catch (ClassNotFoundException e) {
30             e.printStackTrace();
31         } catch (IOException e) {
32             e.printStackTrace();
33         }
34     }
35 }
36 
37 // Serializable--標記型介面, 沒有實際的方法, 知識用來表示這個類可以被序列化
38 class Test implements Serializable {
39     
40     private static final long serialVersionUID = 1L;
41     
42     String name = "hanqi";
43     int i = 3;
44     int j = 15;
45     transient double d = 12.345; // 透明的, 表示這個屬性在寫入流的時候不予考慮
46         
47     
48     @Override
49     public String toString() {
50         return "Test [name=" + name + ", i=" + i + ", j=" + j + ", d=" + d + "]";
51     }
52 }