Java之文件的随机访问和读写RandomAccessFile

 package FileDemo;

 import java.io.IOException;
import java.io.RandomAccessFile; public class RandomAccessFileDemo { /**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException { writeAccess();
readAccess();
randomWrite();
} // 随机写入数据,可以实现对已有数据的修改,因为可以使用seek()方法改变文件指针的位置
private static void randomWrite() throws IOException {
RandomAccessFile raf = new RandomAccessFile("random.txt", "rw");
raf.seek(8 * 4);//将文件指针移动到指定位置
System.out.println(raf.getFilePointer());
raf.write("Ruby".getBytes());
raf.writeInt(99);
} private static void readAccess() throws IOException {
RandomAccessFile raf = new RandomAccessFile("random.txt", "r");
System.out.println(raf.getFilePointer());
raf.seek(8);// 用于实现随机读取文件中的数据,数据最号有规律
System.out.println(raf.getFilePointer());
byte buf[] = new byte[4];
raf.read(buf);
String name = new String(buf);
int age = raf.readInt();
System.out.println("name=" + name);
System.out.println("age=" + age);
System.out.println(raf.getFilePointer()); } private static void writeAccess() throws IOException {
// rw:当这个文件不存在,会创建文件,当文件已经存在,不会创建,所以不会出现和输出流一样的覆盖
RandomAccessFile raf = new RandomAccessFile("random.txt", "rw");
raf.write("Java".getBytes());
raf.writeInt(97);
raf.write("python".getBytes());
raf.write(98);
raf.close();
} }
上一篇:Caused by:java.sql.SQLException:ORA-00923


下一篇:Integer自动装箱拆箱bug,创建对象在-128到127