天天看點

IO流

1流的分類:

按資料機關分:位元組流(InputStream、OutputStream),字元流(Reader、Writer)

按流向分:輸入流,輸出流

按流的角色分:節電流、處理流

IO流
詳細點有如下
IO流
2 流的轉換:InputStreamReader和OutputStreamWriter
IO流

3 RandomAccessFile類:程式可以跳到任意位置來讀寫檔案。

①long getFilePointer():擷取檔案記錄指針的目前位置

②void seek(long pos):将檔案記錄指針定位到 pos 位置

③構造器:

public RandomAccessFile(File file, String mode)

public RandomAccessFile(String name, String mode)

關于mode:該參數指定RandomAccessFile的通路模式

如:

r: 以隻讀方式打開

rw:打開以便讀取和寫入

rwd:打開以便讀取和寫入;同步檔案内容的更新

rws:打開以便讀取和寫入;同步檔案内容和中繼資料的更

代碼舉例:

1 import java.io.File;
 2 import java.io.FileNotFoundException;
 3 import java.io.RandomAccessFile;
 4 
 5 import org.junit.Test;
 6 
 7 public class TestRandomAccessFile {
 8     @Test
 9     public void test1() throws Exception {
10         RandomAccessFile raf = new RandomAccessFile(new File("hello.txt"), "rw");
11     
12 //        raf.seek(7);
13 //        raf.write("xyz".getBytes());
14 //        
15 //        raf.close();
16         //1.
17         raf.seek(7);
18         StringBuffer sb = new StringBuffer();
19         byte[] b = new byte[20];
20         int len;
21         while((len = raf.read(b)) != -1){
22             String str = new String(b,0,len);
23             sb.append(str);
24         }
25         //2.
26         raf.seek(7);
27         raf.write("xyz".getBytes());
28         raf.write(sb.toString().getBytes());
29         
30         raf.close();
31     }
32 }      
下一篇: 集合