• Java—IO流 RandomAccessFile类


    • RandomAccessFile
    1. java提供的对文件内容的访问,既可以读文件,也可以写文件。
    2. 支持随机访问文件,可以访问文件的任意位置。
    3. java文件模型,在硬盘上的文件是byte byte byte存储的,是数据的集合
    4. 打开文件,有两种模式,“rw”读写、“r”只读;RandomAccessFile raf = new RandomAccessFile(file, "rw");,文件指针,打开文件时指针在开头 point = 0;
    5. 写方法, raf.write()-->只写一个字节(后八位),同时指针指向下一个位置,准备再次写入
    6. 读方法,int b = raf.read()-->读一个字节
    7. 文件读写完成以后一定要关闭(Oracle官方说明)

     RafDemo.java

    package com.test.io;
    
    import java.io.File;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import java.util.Arrays;
    
    public class RafDemo {
    
        public static void main(String[] args) throws IOException {
            File demo = new File("demo");
            if (!demo.exists()) {
                demo.mkdir();
            }
            File file = new File(demo, "raf.dat");
            if (!file.exists()) {
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rw");
            System.out.println(raf.getFilePointer());
            
            raf.write('A');//一个char型占两个字节,但是write一次只写入一个字节(A字符的后八位)
            System.out.println(raf.getFilePointer());
            raf.write('B');
            
            int i = 0x7fffffff;
            raf.write(i >>> 24);//写入i的高八位
            raf.write(i >>> 16);
            raf.write(i >>> 8);
            raf.write(i);
            System.out.println(raf.getFilePointer());
            //直接写入一个int
            raf.writeInt(i);
            
            String s = "你";
            byte[] b = s.getBytes("utf8");
            raf.write(b);
            System.out.println(raf.length());
            
            //读文件,必须把指针移到头部
            raf.seek(0);
            //一次性读取,把文件中的内容都读到字节数组中
            byte[] buf = new byte[(int) raf.length()];
            raf.read(buf);
            System.out.println(Arrays.toString(buf));
            for (byte c : buf) {
                System.out.print(Integer.toHexString(c & 0xff) + "  ");
            }
            //关闭文件
            raf.close();
        }
    
    }

      执行结果:

    0
    1
    6
    13
    [65, 66, 127, -1, -1, -1, 127, -1, -1, -1, -28, -67, -96]
    41  42  7f  ff  ff  ff  7f  ff  ff  ff  e4  bd  a0  
  • 相关阅读:
    how to pass a Javabean to server In Model2 architecture.
    What is the Web Appliation Archive, abbreviation is "WAR"
    Understaning Javascript OO
    Genetic Fraud
    poj 3211 Washing Clothes
    poj 2385 Apple Catching
    Magic Star
    关于memset的用法几点
    c++ 函数
    zoj 2972 Hurdles of 110m
  • 原文地址:https://www.cnblogs.com/tianxintian22/p/6820691.html
Copyright © 2020-2023  润新知