随机访问文件

 1 /**
 2  * 测试随机访问文件
 3  */
 4 public class TestRandomAccessFile {
 5     
 6     @Test
 7     public void test1(){
 8         try {
 9             RandomAccessFile raf = new RandomAccessFile("d:\\111.txt","rw");
10             //raf.seek(3);
11             byte[] buf = new byte[2] ;
12             int len = 0 ;
13             while((len = raf.read(buf)) != -1){
14                 System.out.println(new String(buf,0,len));
15             }
16             raf.seek(raf.getFilePointer() - 1);
17             //raf.skipBytes();
18             len = 0 ;
19             while((len = raf.read(buf)) != -1){
20                 System.out.println(new String(buf,0,len));
21             }
22             raf.close();
23         } catch (Exception e) {
24             e.printStackTrace();
25         }
26     }
27     
28     /**
29      * 设置文件大小
30      */
31     @Test
32     public void testRafLength(){
33         try {
34             RandomAccessFile raf = new RandomAccessFile("d:\\222.txt","rw");
35             raf.setLength(1024);
36             raf.close();
37         } catch (Exception e) {
38             e.printStackTrace();
39         }
40     }
41     
42     /**
43      * 设置文件大小
44      */
45     @Test
46     public void testRafConent(){
47         try {
48             RandomAccessFile raf = new RandomAccessFile("d:\\222.txt","rw");
49             byte[] buf = new byte[10];
50             raf.read(buf);
51             System.out.println();
52         } catch (Exception e) {
53             e.printStackTrace();
54         }
55     }
56         
57 }
58  

 

posted on 2017-04-29 15:45  艺海浮台  阅读(167)  评论(0)    收藏  举报