package demo.io;
import java.io.IOException;
import java.io.RandomAccessFile;
class 随机访问文件RandomAccessFile {
public static void main(String[] args) throws IOException {
outputFile();//写入文件
inputFile();//读取文件
}
//读取文件
private static void inputFile() throws IOException {
RandomAccessFile raf = new RandomAccessFile("后期设备的配置文件.properties", "r");//只读
System.out.println("文件长度(字节):" + raf.length());
// raf.seek(8 * 1);//指针指向指定位置
// raf.skipBytes(8 * 1);//向后跳过指定字节数
byte[] buf = new byte[4];
raf.read(buf);
System.out.println(new String(buf));
// System.out.println(raf.readInt());
System.out.println("目前指针位置: " + raf.getFilePointer());
raf.close();
}
//写入文件
private static void outputFile() throws IOException {
RandomAccessFile raf = new RandomAccessFile("后期设备的配置文件.properties", "rw");//既读又写
raf.write("张三".getBytes());
// raf.writeInt(609);
raf.write("李四".getBytes());
// raf.writeInt(97);
raf.close();
}
}
/**
* raf.writeBytes("张三");//舍弃每个字符的高8位,那么剩下8位就是byte,不可取
* raf.write(609);//同样只剩最后1个字节
*/
随机访问文件RandomAccessFile
Java RandomAccessFile 操作实例
最新推荐文章于 2022-03-28 15:11:40 发布
该博客展示了如何使用Java的RandomAccessFile类进行文件的读写操作。主要内容包括通过'rw'模式创建文件,写入字符串并跳过指定字节,然后读取文件内容并打印当前指针位置。博客还包含注释,解释了不同方法的功能,如writeBytes和writeInt。
1017

被折叠的 条评论
为什么被折叠?



