RandomAccessFile:

  翻译过来就是任意修改文件,可以从文件的任意位置进行修改,迅雷的下载就是通过多个线程同时读取下载文件。例如,把一个文件分为四

部分,四个线程同时下载,最后进行内容拼接

public class RandomAccessFile implements DataOutput, DataInput, Closeable {
public RandomAccessFile(String name, String mode);
public RandomAccessFile(File file, String mode);
}

RandomAccessFile实现了DataOutput和DataInput接口,说明可以对文件进行读写

有两种构造方法,一般使用第二种方式

第二个参数mode,有四种模式

Java IO(二)--RandomAccessFile基本使用-LMLPHP

代码实例:

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Student { private int id;
private String name;
private int sex;
}
public static void main(String[] args) throws Exception{
String filePath = "D:" + File.separator + "a.txt";
RandomAccessFile accessFile = new RandomAccessFile(new File(filePath), "rw");
Student student = new Student(1004, "sam", 1);
accessFile.writeInt(student.getId());
accessFile.write(student.getName().getBytes());
accessFile.writeInt(student.getSex());
}

打开a.txt:

Java IO(二)--RandomAccessFile基本使用-LMLPHP

  发现内容为乱码,这是因为系统只识别ANSI格式的写入,其他格式都是乱码。当然如果你在软件、IDE书写txt文件,打开没有乱码,是因为

已经替我们转格式了。

writeUTF():

public static void main(String[] args) throws Exception{
String filePath = "D:" + File.separator + "a.txt";
RandomAccessFile accessFile = new RandomAccessFile(new File(filePath), "rw");
Student student = new Student(1004, "sam", 1);
// accessFile.writeInt(student.getId());
// accessFile.write(student.getName().getBytes());
// accessFile.writeInt(student.getSex());
accessFile.writeUTF(student.toString());
}

writeUTF()以与系统无关的方式写入,而且编码为utf-8,打开文件:

Java IO(二)--RandomAccessFile基本使用-LMLPHP

文件读取:

public static void main(String[] args) throws Exception{
String filePath = "D:" + File.separator + "a.txt";
RandomAccessFile accessFile = new RandomAccessFile(new File(filePath), "rw");
Student student = new Student();
String s = accessFile.readUTF();
System.out.println(s);
}

输出结果:

Student(id=1004, name=sam, sex=1)

这里需要注意,如果是先写文件,然后立刻读取,需要调用accessFile.seek(0);把指针指向首位,因为文件写入最终指针指向末尾了。=

追加内容到末尾:

public static void main(String[] args) throws Exception{
String filePath = "D:" + File.separator + "a.txt";
RandomAccessFile accessFile = new RandomAccessFile(new File(filePath), "rw");
accessFile.seek(accessFile.length());
accessFile.write("最佳内容".getBytes());
}

Java IO(二)--RandomAccessFile基本使用-LMLPHP

我们首先把指针移动到文件内容末尾

04-18 03:20