码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2019-06-18 20:04:37      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:img   mamicode   方式   src   div   mod   image   修改文件   exce   

RandomAccessFile:

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

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

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

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

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

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

技术图片

代码实例:

@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:

技术图片

  发现内容为乱码,这是因为系统只识别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,打开文件:

技术图片

文件读取:

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基本使用

标签:img   mamicode   方式   src   div   mod   image   修改文件   exce   

原文地址:https://www.cnblogs.com/huigelaile/p/11047101.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!