//随机存取文件流的使用 //该类的实例支持读取和写入随机访问文件。 随机访问文件的行为类似于存储在文件系统中的大量字节。 // 有一种游标,或索引到隐含的数组,称为文件指针 ; 输入操作读取从文件指针开始的字节,并使文件指针超过读取的字节。 // 如果在读/写模式下创建随机访问文件,则输出操作也可用; 输出操作从文件指针开始写入字节,并将文件指针提前到写入的字节。 // 写入隐式数组的当前端的输出操作会导致扩展数组。 文件指针可以通过读取getFilePointer方法和由设置seek方法。 //构造器 //RandomAccessFile(File file, String mode) //创建一个随机访问文件流从File参数指定的文件中读取,并可选地写入文件。 //RandomAccessFile(String name, String mode) //创建随机访问文件流,以从中指定名称的文件读取,并可选择写入文件。 /*1.RandomAccessFile直接继承于Object类,实现了DataInput和DataOutput接口 * 2.RandomAccessFile既可以作为一个输入流有可以作为一个输出流 * 3.如果RandomAccessFile作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建,如果存在,则会对原有文件内容进行覆盖 * 4.通过相关操作,可以实现RandomAccessFile的插入操作,但是效率不高 * * **/
class RandomAccessFile_use {
public static void insert(int site,File file,String s) {
File filetemp= null;
BufferedOutputStream outputStream= null;
BufferedInputStream inputStream= null;
RandomAccessFile rw = null;
try {
rw = new RandomAccessFile(file, "rw");
filetemp = new File("src/temp.txt");
outputStream = new BufferedOutputStream(new FileOutputStream(filetemp));
inputStream = new BufferedInputStream(new FileInputStream(filetemp));
//将文件指针调到特定索引位置
rw.seek(site);
byte[] bytes=new byte[5];
int len;
//将余下内容写出到一个介质文件中
while ((len= rw.read(bytes))!=-1){
outputStream.write(bytes);
}
//重新指定指针
rw.seek(site);
//插入内容到文件
rw.write(s.getBytes());
//将余下内容重新写入文件中
while ((len=inputStream.read(bytes))!=-1){
rw.write(bytes, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outputStream!=null){
try {
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (rw!=null){
try {
rw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//关闭流
//删除文件
filetemp.delete();
}
public static void main(String[] args) throws IOException {
// RandomAccessFile rw = null;//读和写
// try {
// rw = new RandomAccessFile(new File("src/IO_use/hello.txt"), "rw");
// byte[] bytes=new byte[100];
// int len;
// rw.seek(3);
// //会对文件写入的地方进行覆盖
// rw.write("a".getBytes());
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// if (rw!=null) {
// try {
// rw.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
insert(1, new File("src/IO_use/hello1mystery1.txt"), "a");
}
}