(随机流)RandomAccessFile

来源:互联网 发布:windows lua 下载 编辑:程序博客网 时间:2024/06/06 09:47
/**
* 随机存储文件  RandomAccessFile
* 既可以当输入流  也可以当输出流
* 支持从文件的开头读取、写入
* 支持从文件的任意位置读取、写入

* 此方法实现了从文件的任意位置插入内容
*/
public static void suiJiInsert(){
//提供随机访问的流
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(new File("hello.txt"), "rw");
//调取光标到指定插入的位置,开始读取指针后面的内容
raf.seek(3);
//读取指定位置后面的内容
byte[] b = new byte[10];
int len;
StringBuffer sb = new StringBuffer();
while((len = raf.read(b)) != -1){
//把指定光标后面的内容暂时存储在sb中
sb.append(new String(b, 0, len));
}
//在把指针调回原来的位置开始进行写入操作
raf.seek(3);
//插入xy两个字符
raf.write("xy".getBytes());
//在xy后面添加原有的内容
raf.write(sb.toString().getBytes());
}  catch (IOException e) {
e.printStackTrace();
}finally {
if(raf != null){
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}

/**
* 用随机流实现复制功能的操作
*/
public static void shuiJi(){
RandomAccessFile raf1 = null;
RandomAccessFile raf2 = null;
try {
//r表示只读
raf1 = new RandomAccessFile(new File("hello.txt"), "r");
//rw表示可读取、可写入
raf2 = new RandomAccessFile(new File("hello1.txt"), "rw");

byte[] b = new byte[1024];
int len;
while((len = raf1.read(b)) != -1){
raf2.write(b, 0, len);
}
}  catch (IOException e) {
e.printStackTrace();
}finally {
if(raf2 != null){
try {
raf2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(raf1 != null){
try {
raf1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

0 0
原创粉丝点击