zoukankan      html  css  js  c++  java
  • Java IO(二)--RandomAccessFile基本使用

    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字符串大小写转换
    实现对字符串数组{"Allen","Smith","James","Martin","Ford"} 求得包含字母a的所有的名字
    将一维数组中的0去掉,不为0的项存入一个新的数组中
    hibernate -- HQL语句总结
    oracle intersect 取交集
    Spring中applicationContext.xml的bean里的id和name属性区别
    spring 源码分析
    python爬虫
  • 原文地址:https://www.cnblogs.com/huigelaile/p/11047101.html
Copyright © 2011-2022 走看看