BufferedInputStream類中的mark(int readlimit)方法
對于BufferedInputStream類中的mark(int readlimit)方法的使用,很多人的疑惑是:參數readlimit究竟起什么作用?
好象給readlimit賦任何整數值結果都是一樣。
2
3 import java.io.*;
4
5 public class BufInputStrm_A {
6
7 public static void main(String[] args) throws IOException {
8 String s = "ABCDEFGHI@JKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
9 byte[] buf = s.getBytes();
10 ByteArrayInputStream in = new ByteArrayInputStream(buf);
11 BufferedInputStream bis = new BufferedInputStream(in, 13);
12 int i = 0;
13 int k;
14 do {
15 k = bis.read();
16 System.out.print((char) k + " ");
17 i++;
18
19 if (i == 4) {
20 bis.mark(8);
21 }
22 } while (k != '@');
23
24 System.out.println();
25
26 bis.reset();
27 k = bis.read();
28 while (k != -1) {
29
30 System.out.print((char) k + " ");
31 k = bis.read();
32 }
33
34 }
35 }
36
備注:為了方便說明問題,我們假設要讀取的是一個字符串(第8行代碼),同時把緩存的大小設置為了13(第11行代碼)。
在第20行代碼處調用了mark(int readlimit)方法,但無論給該方法傳-1、0、13、100程序輸出的結果都是一樣:


在官方的API幫助文檔中,對于readlimit這個參數的解釋是:
readlimit
- the maximum limit of bytes that can be read before the mark position becomes invalid.其實,這里的最大字節數(the maximum limit of bytes)是指調用reset()方法之后,讀取超過readlimit指定的字節數,標記維(the mark position)會失效,如果這時再次調用reset()方法,會出現Resetting to invalid mark異常。例如下面的程序:
2
3 import java.io.*;
4
5 public class BufInputStrm_A {
6
7 public static void main(String[] args) throws IOException {
8 String s = "ABCDEFGHI@JKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
9 byte[] buf = s.getBytes();
10 ByteArrayInputStream in = new ByteArrayInputStream(buf);
11 BufferedInputStream bis = new BufferedInputStream(in, 13);
12 int i = 0;
13 int k;
14 do {
15 k = bis.read();
16 System.out.print((char) k + " ");
17 i++;
18
19 if (i == 4) {
20 bis.mark(8);
21 }
22 } while (k != '@');
23
24 System.out.println();
25
26 bis.reset();
27 k = bis.read();
28 while (k != -1) {
29
30 System.out.print((char) k + " ");
31 k = bis.read();
32 }
33
34 System.out.println();
35
36 bis.reset();
37 k = bis.read();
38 while (k != -1) {
39 System.out.print((char) k + " ");
40 k = bis.read();
41
42 }
43
44 }
45 }
46
如果我們在第一次調用了reset()方法之后,控制讀入的字節不超過8個,程序就會正常執行,例如我們對上面的程序的26-32代碼用下面的代碼替換,程序就可以正常運行了。
int j = 1;
k = bis.read();
while (j < 9) {
System.out.print((char) k + " ");
k = bis.read();
j++;
}
補充:
在mark(int readlimit)方法的代碼中,readlimit的值會賦給數據域marklimit,如果marklimit的值大于緩沖區的值BufferedInputStream會對緩沖區的大小進行調整,調整為marklimit的值。
----------------------------------
把人做到寬容,把技術做到強悍。
posted on 2008-04-24 14:45 OldBoy 閱讀(1461) 評論(5) 編輯 收藏 所屬分類: Java基礎