⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 testrandomaccessfile.java

📁 本书是一本为Java学习者在基础内容学习结束后进行课程设计时提供参考的指导书
💻 JAVA
字号:
package apibook.c3.s5;import java.io.*;//测试RandomAccessFile类//功能:对随机文件进行读写public class TestRandomAccessFile {  public TestRandomAccessFile() {  }  public static void main(String[] args) {    try {      String filename = "TestRandomAccessFile.txt";        RandomAccessFile raf = new RandomAccessFile(filename, "rw");//读写方式打开        char a = 'a';        byte b = 2;        String c = "abc";        short d = 4;        byte[] b2 = {'a', 'b', 'c'};        //写入测试数据        long file_start = raf.getFilePointer();//得到文件指针        raf.write(b);//字节        raf.write(b2, 0, b2.length);//字节数组        raf.writeBoolean(true);//布尔值        raf.writeChar(a);//字符        raf.writeBytes(c);//作为字节写入字符串        raf.writeChars(c);//作为字符写入字符串        raf.writeDouble(123.456);//double        raf.writeFloat(123.456f);//float        raf.writeInt(678);//int        raf.writeLong(678l);//long        raf.writeShort(d);//short        raf.writeUTF(c);//用utf编码的字符        raf.writeUTF("abc\n");//用utf编码的字符串        raf.write(b);//字节        raf.writeShort(d);//short        System.out.println("Length of file: " + raf.length());//文件长度        //读回测试数据        raf.seek(file_start);//移到文件头        b2 = new byte[1];        b = raf.readByte();//读字节        System.out.println("Byte: " + b);        raf.read(b2);//读字节数组        System.out.println("Byte[0]: " + (char)b2[0]);        raf.read(b2, 0, b2.length);//读字节数组        System.out.println("Byte[0]: " + (char)b2[0]);        int ub = raf.readUnsignedByte();//读入无符号的字节        System.out.println("Unsigned Byte: " + b);        System.out.println("Boolean: " + raf.readBoolean());        a = raf.readChar();//读字符        System.out.println("Char: " + a);        byte[] b3 = new byte[3];        raf.readFully(b3);//读字节数组        System.out.println("readFully: " + (char)b3[0] + (char)b3[1] +                           (char)b3[2]);        raf.skipBytes(6); //跳过字符串 'abc'        double d1 = raf.readDouble();//读double        float f1 = raf.readFloat();//float        int i = raf.readInt();//int        long l = raf.readLong();//long        short s = raf.readShort();//short        String str = raf.readUTF();//读utl编码的字符串        ub = raf.readUnsignedByte();        int us = raf.readUnsignedShort();        System.out.println("UTF String" + str);//输出结果        raf.close();//关闭文件    } catch (IOException e) {        System.err.println(e);    }  }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -