徹底明白Java的IO系統 轉貼

2021-03-31 08:57:00 字數 1840 閱讀 5162

//1b. 接收鍵盤的輸入

bufferedreader stdin =

new bufferedreader(

new inputstreamreader(system.in));

system.out.println("enter a line:");

system.out.println(stdin.readline());

//2. 從乙個string物件中讀取資料

stringreader in2 = new stringreader(s2);

int c;

while((c = in2.read()) != -1)

system.out.println((char)c);

in2.close();

//3. 從記憶體取出格式化輸入

trycatch(eofexception e)

//4. 輸出到檔案

trycatch(eofexception ex)

//5. 資料的儲存和恢復

trycatch(eofexception e)

//6. 通過randomaccessfile操作檔案

randomaccessfile rf =

new randomaccessfile("f://nepalon// rtest.dat", "rw");

for(int i=0; i<10; i++)

rf.writedouble(i*1.414);

rf.close();

rf = new randomaccessfile("f://nepalon// rtest.dat", "r");

for(int i=0; i<10; i++)

system.out.println("value " + i + ":" + rf.readdouble());

rf.close();

rf = new randomaccessfile("f://nepalon// rtest.dat", "rw");

rf.seek(5*8);

rf.writedouble(47.0001);

rf.close();

rf = new randomaccessfile("f://nepalon// rtest.dat", "r");

for(int i=0; i<10; i++)

system.out.println("value " + i + ":" + rf.readdouble());

rf.close();}}

關於**的解釋(以區為單位):

1區中,當讀取檔案時,先把檔案內容讀到快取中,當呼叫in.readline()時,再從快取中以字元的方式讀取資料(以下簡稱「快取位元組讀取方式」)。

1b區中,由於想以快取位元組讀取方式從標準io(鍵盤)中讀取資料,所以要先把標準io(system.in)轉換成字元導向的stream,再進行bufferedreader封裝。

2區中,要以字元的形式從乙個string物件中讀取資料,所以要產生乙個stringreader型別的stream。

4區中,對string物件s2讀取資料時,先把物件中的資料存入快取中,再從緩衝中進行讀取;對testio.out檔案進行操作時,先把格式化後的資訊輸出到快取中,再把快取中的資訊輸出到檔案中。

5區中,對data.txt檔案進行輸出時,是先把基本型別的資料輸出屋快取中,再把快取中的資料輸出到檔案中;對檔案進行讀取操作時,先把檔案中的資料讀取到快取中,再從快取中以基本型別的形式進行讀取。注意in5.readdouble()這一行。因為寫入第乙個writedouble(),所以為了正確顯示。也要以基本型別的形式進行讀取。

6區是通過randomaccessfile類對檔案進行操作。

徹底明白Java的IO系統

1b.接收鍵盤的輸入 bufferedreader stdin new bufferedreader new inputstreamreader system.in system.out.println enter a line system.out.println stdin.readline 2...

徹底明白Java的IO系統

1b.接收鍵盤的輸入 bufferedreader stdin new bufferedreader new inputstreamreader system.in system.out.println enter a line system.out.println stdin.readline 2...

徹底明白Java的IO系統

1b.接收鍵盤的輸入 bufferedreader stdin new bufferedreader new inputstreamreader system.in system.out.println enter a line system.out.println stdin.readline 2...