RandomAccessFile
读写操作
写:
void write(int d):写一个字节,写的是读取int的低8位
void write(byte[] b):写若干字节,写出的字节量就是给定的数组的长度.换句话说,就是将数组中所有字节都写出
void write(byte[] b,int offset,int len):将数组中从iffset连续开始写入len个字节
例如 raf.write(byte,5,5);
void write(byte[] b,int offset,int len)
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileDemo {
public static void main(String[] args) throws IOException {
File file=new File("buf.dat");
if(!file.exists()){file.createNewFile();}
RandomAccessFile raf=new RandomAccessFile(file,"rw");
//创建一个字节数组,该数组中的内容是要写出的数据
byte[] data={0,1,2,3,4,5,6,7,8,9};
raf.write(data);//将字节数组内容全部写出
//只写该数组中的1-5
raf.write(data,1,5);
raf.close();
}
}
读:
int read():一次读取一个字节,并以int形式返回. 该int值只有低8位有效. 若返回值位-1,说明读取到了文件末尾.
EOF:文件末尾 end of file
int read(byte[] b):尝试读取给定的字节数组长度的字节并存入数组,返回实际读取的字节数
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;
public class RandomAccessFileDemo02 {
public static void main(String[] args) throws IOException {
File file=new File("buf.dat");
RandomAccessFile raf=new RandomAccessFile(file,"rw");
//读取文件所有字节并输出
int d=-1;
/**
* 读取一个字节,若返回值是-1,则到了末尾
*/
while((d=raf.read())!=-1){
System.out.println(d+"");
}
/**
* 批量读取数据
*/
raf.seek(0);
//创建一个可以保存30个字节的数组
byte[] buf=new byte[30];
System.out.println("实际读取的字节数"+raf.read(buf));//15
System.out.println(Arrays.toString(buf));//[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
byte[] buff=new byte[15];
System.arraycopy(buf, 0, buff, 0, 15);
System.out.println(Arrays.toString(buff));//[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5]
raf.close();
}
}