RandomAccessFile(随机读写文件)
1、直接继承Object.
主要功能是完成随机读写功能,可以读取指定位置的内容。
2、构造方法:只能操作文件
public RandomAccessFile(File file,String mode) 创建一个随机访问文件流读,随意写来,由 File参数指定的文件。
public RandomAccessFile(String name,String mode) 创建一个随机访问文件流,并可选择地写入到具有指定名称的文件中。
3、文件的打开模式(mode):
“r” 以只读方式打开。调用结果对象的任何 write 方法都将导致抛出 IOException。
“rw” 打开以便读取和写入。如果该文件尚不存在,则尝试创建该文件。
4、RandomAccessFile常用方法:
void seek(long pos)设置文件指针偏移量,在该位置准备开始读写。
int skipBytes(int n)尝试跳过输入的 n 个字节并丢弃跳过的字节.返回实际跳过的字节数
long getFilePointer()获取此文件中的当前偏移量
long length()返回此文件的长度。
void write(int)向此文件写入指定的字节。
void write(byte[])将 b.length 个字节从指定 byte 数组写入到此文件,并从当前文件指针开始。
void write(byte[] b, int off, int len)
int read()从此文件中读取一个数据字节。
int read(byte[] b)将最多 b.length 个数据字节从此文件读入 byte 数组。
int read( byte[] b, int off, int len)
void writeBytes(String s) 以字节为单位写出字符串,无法写出中文
void writeChars(String s) ,每个字符占两个位置,可以写出中文,使用unicode编码。
void writeUTF(String str)使用utf-8编码方式将一个字符串写出到该文件 ,可以写出中文
void writeBoolean(boolean v)
void writeByte(int v)
void writeChar(int v)
void writeInt(int v)
package raf;
import java.io.*;
public class RandomAccessFileDemo {
public static void main(String[] args) {
File f=new File("c:"+File.separator+"test.txt");
RandomAccessFile raf=null;
try {
raf=new RandomAccessFile(f,"rw");
raf.writeBoolean(false);
raf.writeChars("Hello");
raf.writeChar('中');
System.out.println("写入成功!");
raf.seek(9);
// raf.skipBytes(9);
System.out.println("当前文件指针位置:"+raf.getFilePointer());
System.out.println(raf.readChar());
raf.seek(3);
System.out.println("当前文件指针位置:"+raf.getFilePointer());
System.out.println(raf.readChar());
raf.seek(11);
System.out.println("当前文件指针位置:"+raf.getFilePointer());
System.out.println(raf.readChar());
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
运行结果:
package raf;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RafString {
public static void main(String[] args) {
File f=new File("c:"+File.separator+"test.txt");
RandomAccessFile raf=null;
try {
raf=new RandomAccessFile(f,"rw");
raf.writeBytes("中华人民共和国"); // 会丢弃高八位的方式写入字符串的每个字符
raf.writeChars("小王子"); // writeChars(xx)将字符串中的每个字符以两个字节的形式写入
raf.seek(7); // 设置文件指针的位置
System.out.println(raf.readChar());
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
运行结果: