public class Test { public static void main(String[] args) throws IOException, InterruptedException { test1(); // test2(); test3(); } private static void test1() throws IOException{ String filePath = "F:/shanch/temp/a.txt"; //RandomAccessFile没有会自动创建文件 RandomAccessFile raFile = new RandomAccessFile(filePath,"rw"); System.out.println(raFile.getFilePointer()); //setLength会往文件里面写入空白串 即byte 00 raFile.setLength(36); raFile.writeBytes("0123456789abcdefghijklmnopqrstuvwxyz1111"); System.out.println(raFile.getFilePointer()); //会将多出的1111截掉 raFile.setLength(36); System.out.println(raFile.getFilePointer()); raFile.seek(20); System.out.println(raFile.getFilePointer()); raFile.skipBytes(6); System.out.println(raFile.getFilePointer()); //skipbytes不会使指针将超过文件长度 raFile.skipBytes(20); System.out.println(raFile.getFilePointer()); //seek如果位置超过文件长度,会将文件扩大 raFile.seek(50); System.out.println(raFile.getFilePointer()); raFile.write(100); raFile.setLength(36); } private static void test2() throws IOException{ String filePath = "F:/shanch/temp/a.txt"; RandomAccessFile raFile = new RandomAccessFile(filePath,"rw"); raFile.seek(10); //read读取当前指针的byte 读取之后指针下移一个byte System.out.println((char)raFile.read()); System.out.println(raFile.getFilePointer()); raFile.seek(10); raFile.write(0);//替换a 而非插入 raFile.write(0);//替换b raFile.write(0);//替换c } private static void test3() throws IOException, InterruptedException{ final String filePath = "F:/shanch/temp/a.txt"; RandomAccessFile raFile = new RandomAccessFile(filePath,"rw"); FileChannel fChannel = raFile.getChannel(); //当文件锁住时,不可修改 // fChannel.lock(); //程序退出时会自动释放锁 //position与FilePointer一致 fChannel.position(10); System.out.println(raFile.getFilePointer()); raFile.seek(20); System.out.println(fChannel.position()); //清空文件,从文件头开始,只保留指定字节数 fChannel.truncate(50); fChannel.lock(10, 10, true); //FileChannel与RandomAccessFile的写方法是不同的实现 //FileChannel锁住时,RandomAccessFile将不能写 // raFile.seek(15); // raFile.write(97); //此处会报异常 Thread.currentThread().sleep(2000); new Thread() { public void run(){ try { RandomAccessFile raFile = new RandomAccessFile(filePath,"rw"); raFile.seek(15); System.out.println((char)raFile.read()); raFile.write(26);//另一个程序已锁定文件的一部分,进程无法访问。 // raFile.read(); } catch (IOException e1) { e1.printStackTrace(); } } }.start(); } }