RandomAccessFile类实现对文件内容的随机读写
文件内容的随机操作,重难点在于字符操作,具体查看API
1 package org.zln.io.file; 2 3 import java.io.IOException; 4 import java.io.RandomAccessFile; 5 6 /** 7 * Created by coolkid on 2015/6/21 0021. 8 */ 9 public class TestRandonAccessFile { 10 public static void main(String[] args) throws IOException { 11 // fileReadTest(); 12 RandomAccessFile file = new RandomAccessFile("E:\测试文件.txt","rw"); 13 14 file.writeChars("filename"); 15 16 file.close(); 17 18 } 19 20 private static void fileReadTest() throws IOException { 21 /*文件刚打开 默认读取指针位置 位于 文件的最开始处 0 */ 22 RandomAccessFile file = new RandomAccessFile("E:\测试文件.txt","rw"); 23 24 System.out.println("文件大小:"+file.length()+" 字节"); 25 26 int c; 27 for (int i = 0; i < 10; i++) { 28 c = file.read();//读取一个字节 每次读取后文件指针往后移动一个位置 29 System.out.println("单字节 - 第 "+i+" 次 读取:"+(char)c); 30 } 31 32 file.seek(0); 33 byte[] bytes = new byte[100]; 34 for (int i = 0; i < 10; i++) { 35 file.read(bytes); 36 System.out.println("字节数组 - 第 "+i+" 次 读取:"+new String(bytes)); 37 } 38 39 file.seek(0); 40 String line; 41 for (int i = 0; i < 10; i++) { 42 line = file.readUTF(); 43 System.out.println("UTF - 第 "+i+" 次 读取:"+line); 44 } 45 file.close(); 46 } 47 }