62,615
社区成员
发帖
与我相关
我的任务
分享
import java.io.*;
public class RandomAcessFileDemo {
public static void main(String[] args) throws IOException {
File f = new File("C:" + File.separator + "text.txt");
int length = 0;
RandomAccessFile raf = null;
// 写入
try {
raf = new RandomAccessFile(f, "rw");
String name = "张三";
int age = 15;
byte[] bs = name.getBytes("utf-8");
length = bs.length;
raf.write(bs);
raf.writeInt(age);
} finally {
if (raf != null) {
raf.close();
raf = null;
}
}
// 读取
try {
raf = new RandomAccessFile(f, "rw");
byte[] buffer = new byte[1024];
int len = raf.read(buffer, 0, length); // 上面输入的名字的长度
System.out.println("name:" + new String(buffer, 0, len, "utf-8"));
int age = raf.readInt();
System.out.println("age:" + age);
} finally {
if (raf != null) {
raf.close();
raf = null;
}
}
}
}
import java.io.File;
import java.io.RandomAccessFile;
public class RandomAcessFileDemo {
public static void main(String[] args) throws Exception {
File f = new File("temp.txt");
RandomAccessFile raf = null;
raf = new RandomAccessFile(f, "rw");
String name = "zhangsan";
Integer age = 15;
raf.writeBytes(name);
raf.skipBytes(8);
raf.writeInt(age);
raf.seek(0);//找位置
byte[] b = new byte[8];
raf.read(b);
System.out.println(new String(b));
System.out.println(raf.readInt());
raf.close();
}
}