您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
【第12章:JAVA IO】_RandomAccessFile
发布时间:2020-12-27 14:49:40编辑:雪饮阅读()
RandomAccessFile类提供了对文件的写入功能
如:
import java.io.File;
import java.io.RandomAccessFile;
public class TestJava{
public static void main(String args[]) throws Exception{
File f=new File("d:"+File.separator+"20201227.txt");
RandomAccessFile rdf=new RandomAccessFile(f,"rw");
String name="kasumi ";
int age=24;
rdf.writeBytes(name);
rdf.writeInt(age);
name="ayane ";
age=24;
rdf.writeBytes(name);
rdf.writeInt(age);
name="snowDrin";
age=18;
rdf.writeBytes(name);
rdf.writeInt(age);
rdf.close();
}
}
D:\>javac TestJava.java
D:\>java TestJava
D:\>type 20201227.txt
kasumi ayane snowDrin
不过在有些地方上面会显示乱码
另外就是上面我们写入的时候每次写入的String长度都是8
RandomAccessFile类提供了对文件的读取功能
由于我们上面写入的时候写入的String长度每次都是8,所以
import java.io.File;
import java.io.RandomAccessFile;
public class TestJava{
public static void main(String args[]) throws Exception{
File f=new File("d:"+File.separator+"20201227.txt");
RandomAccessFile rdf=new RandomAccessFile(f,"rw");
String name = null ;
int age = 0 ;
byte b[] = new byte[8] ; // 开辟byte数组
// 读取第二个人的信息(String刚才我们是8个字节,而int固定为4个字节)
rdf.skipBytes(12) ; // 跳过第一个人的信息
for(int i=0;i<b.length;i++){
b[i] = rdf.readByte() ; // 读取一个字节
}
name = new String(b) ; // 将读取出来的byte数组变为字符串
age = rdf.readInt() ; // 读取数字
System.out.println("第二个人的信息 --> 姓名:" + name + ";年龄:" + age) ;
// 读取第一个人的信息
rdf.seek(0) ; // 指针回到文件的开头
for(int i=0;i<b.length;i++){
b[i] = rdf.readByte() ; // 读取一个字节
}
name = new String(b) ; // 将读取出来的byte数组变为字符串
age = rdf.readInt() ; // 读取数字
System.out.println("第一个人的信息 --> 姓名:" + name + ";年龄:" + age) ;
}
}
D:\>javac TestJava.java
D:\>java TestJava
第二个人的信息 --> 姓名:ayane ;年龄:24
第一个人的信息 --> 姓名:kasumi ;年龄:24
关键字词:java,RandomAccessFile