qileilove

          blog已經轉移至github,大家請訪問 http://qaseven.github.io/

          Java流緩沖區問題

           聽著張孝祥老師關于緩沖區知識的課,發現還是有一些沒有掌握,動手試了一下,果然發現了問題。

            先講一下關于java緩沖區的知識,應用程序和IO設備之間存在一個緩沖區,一般流是沒有緩沖區的,但是如果存在緩沖區,就會發現很大的問題。

            錯誤代碼如下:為了確保問題發生,我使用了BufferedOutputStream,使得手動構造出了一個緩沖區。

          1. import java.io.*;  
          2. public class Test {  
          3.     public static void main(String[] args) throws Exception{  
          4.         DataOutputStream out = new DataOutputStream(  
          5.                             new BufferedOutputStream(  
          6.                             new FileOutputStream("1.txt")));  
          7.         out.writeChars("hello");  
          8.         FileInputStream in = new FileInputStream("1.txt");  
          9.         int len = in.available();  
          10.         byte[] b = new byte[len];  
          11.         int actlen = in.read(b);  
          12.         String str = new String(b);  
          13.         System.out.println(str);  
          14.           
          15.     }     
          16. }

            發現什么問題了嗎?

            因為如果沒有緩沖區,應用程序每次IO都要和設備進行通信,效率很低,因此緩沖區為了提高效率,當寫入設備時,先寫入緩沖區,等到緩沖區有足夠多的數據時,就整體寫入設備。這就是問題所在,上個例子中,當我們寫入hello時,由于hello占用空間很小,所以暫時存放在緩沖區中,后來輸入流想要從文件中讀取,但是由于文件中沒有字節,所以不能讀取hello。

            這里,解決方法很簡單,只要調用out.flush() 或者out.close()即可,這是把緩沖區的數據手動寫入文件。

            正確代碼如下:

          1. import java.io.*;  
          2. public class Test {  
          3.     public static void main(String[] args) throws Exception{  
          4.         DataOutputStream out = new DataOutputStream(  
          5.                             new BufferedOutputStream(  
          6.                             new FileOutputStream("1.txt")));  
          7.         out.writeChars("hello");  
          8.         out.close();//inserted  
          9.         FileInputStream in = new FileInputStream("1.txt");  
          10.         int len = in.available();  
          11.         byte[] b = new byte[len];  
          12.         int actlen = in.read(b);  
          13.         String str = new String(b);  
          14.         System.out.println(str);  
          15.           
          16.     }     
          17. }

           接下來又是我遇到的一個例子,這個例子也很明顯的反應出緩沖區的問題。

          1. import java.io.BufferedReader;  
          2. import java.io.FileReader;  
          3. import java.io.FileWriter;  
          4. import java.io.IOException;  
          5. import java.io.PrintWriter;  
          6. import java.util.Calendar;  
          7. import java.util.Date;  
          8. import java.util.GregorianCalendar;  
          9. import java.util.Scanner;  
          10. import java.util.StringTokenizer;  
          11.   
          12. public class StringTokenizerTest {  
          13.   
          14.     public static void main(String[] args) {  
          15.         Employee[] e = new Employee[3];  
          16.         e[0] = new Employee("Carl Cracker"7500019871215);  
          17.         e[1] = new Employee("Harry Hacker"500001989101);  
          18.         e[2] = new Employee("Tony Tester"400001990315);  
          19.         try {  
          20.             PrintWriter out = new PrintWriter(new FileWriter("1.txt"));  
          21.             writeData(e, out);  
          22.             // out.close();**********************************************************************   
          23.         } catch (Exception e1) {  
          24.             e1.printStackTrace();  
          25.         }  
          26.         System.out.println("*******是否要讀取數據?********");  
          27.         Scanner in1 = new Scanner(System.in);  
          28.         String yes = in1.nextLine();  
          29.         if (yes.equalsIgnoreCase("YES")) {  
          30.             try {  
          31.                 BufferedReader in = new BufferedReader(new FileReader("1.txt"));  
          32.                 Employee[] result = readData(in);  
          33.                 for (int i = 0; i < result.length; i++)  
          34.                     System.out.println(result[i]);  
          35.                 in.close();  
          36.             } catch (Exception e2) {  
          37.                 e2.printStackTrace();  
          38.             }  
          39.         }  
          40.   
          41.     }  
          42.   
          43.     public static Employee[] readData(BufferedReader in) throws IOException {  
          44.         int length = Integer.parseInt(in.readLine());  
          45.         Employee[] e = new Employee[length];  
          46.         for (int i = 0; i < length; i++) {  
          47.             String line = in.readLine();  
          48.             StringTokenizer token = new StringTokenizer(line, "|");  
          49.             String name = token.nextToken();  
          50.             double salary = Double.parseDouble(token.nextToken());  
          51.             int year = Integer.parseInt(token.nextToken());  
          52.             int month = Integer.parseInt(token.nextToken());  
          53.             int day = Integer.parseInt(token.nextToken());  
          54.             e[i] = new Employee(name, salary, year, month, day);  
          55.         }  
          56.         return e;  
          57.     }  
          58.   
          59.     public static void writeData(Employee[] e, PrintWriter out) {  
          60.         out.println(e.length);  
          61.         for (int i = 0; i < e.length; i++) {  
          62.             String name = e[i].getName();  
          63.             double salary = e[i].getSalary();  
          64.             Date date = e[i].getHireDay();  
          65.             Calendar c = new GregorianCalendar();  
          66.             c.setTime(date);  
          67.             int year = c.get(Calendar.YEAR);  
          68.             int month = c.get(Calendar.MONTH) + 1;  
          69.             int day = c.get(Calendar.DAY_OF_MONTH);  
          70.             out.println(name + "|" + salary + "|" + year + "|" + month + "|"  
          71.                     + day);  
          72.   
          73.         }  
          74.         System.out.println("********寫入數據完畢********");  
          75.     }  
          76.   
          77. }  
          78.   
          79. class Employee {  
          80.     public Employee(String n, double s, int year, int month, int day) {  
          81.         name = n;  
          82.         salary = s;  
          83.         GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);  
          84.         hireDay = calendar.getTime();  
          85.     }  
          86.   
          87.     public String getName() {  
          88.         return name;  
          89.     }  
          90.   
          91.     public double getSalary() {  
          92.         return salary;  
          93.     }  
          94.   
          95.     public Date getHireDay() {  
          96.         return hireDay;  
          97.     }  
          98.   
          99.     public void raiseSalary(double byPercent) {  
          100.         double raise = salary * byPercent / 100;  
          101.         salary += raise;  
          102.     }  
          103.   
          104.     public String toString() {  
          105.         return getClass().getName() + "[name=" + name + ",salary=" + salary  
          106.                 + ",hireDay=" + hireDay + "]";  
          107.     }  
          108.   
          109.     private String name;  
          110.   
          111.     private double salary;  
          112.   
          113.     private Date hireDay;  
          114. }

            結果是沒有向文件寫入任何數據,為什么呢?

            唯一的錯誤就在main方法中沒有調用out.close(),把數據從緩沖區刷新到文件。因此用完資源即時關閉是很重要的。

          posted on 2011-11-18 14:37 順其自然EVO 閱讀(1027) 評論(0)  編輯  收藏 所屬分類: 測試學習專欄

          <2011年11月>
          303112345
          6789101112
          13141516171819
          20212223242526
          27282930123
          45678910

          導航

          統計

          常用鏈接

          留言簿(55)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 三原县| 临邑县| 株洲市| 绥德县| 富平县| 仁寿县| 高尔夫| 卓资县| 青州市| 滨州市| 庆安县| 明水县| 饶河县| 宜春市| 德化县| 大同县| 鸡东县| 永济市| 泾阳县| 双流县| 平武县| 桐柏县| 潞城市| 麦盖提县| 旺苍县| 上虞市| 万山特区| 胶州市| 岳池县| 贵溪市| 县级市| 河北省| 平潭县| 合山市| 大理市| 旅游| 朝阳区| 怀仁县| 健康| 图片| 泸定县|