RandomAccessFile的使用
1、RandomAccessFile直接继承于java.lang.Object类实现了DataInput和DataOutput接口
2、RandomAccessFile既可以作为一个输入流,又可以作为一个输出流
3、如果RandomAccessFile作为输入流,写出的文件如果不存在,则在执行过程中自动创建
如果存在,则对阮有文件内容进行覆盖(默认从头覆盖)
public static void main(String[] args){
RandomAccessFile raf1= null;
RandomAccessFile raf2= null;
try {
raf1 = new RandomAccessFile(new File("6.jpg"),"r");
raf2 = new RandomAccessFile(new File("62.jpg"),"rw");
byte[] buffer=new byte[1024];
int len;
while((len=raf1.read(buffer))!=-1){
raf2.write(buffer,0,len);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (raf1!=null){
try {
raf1.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (raf2!=null){
try {
raf2.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}public static void main(String[] args) throws IOException {
RandomAccessFile raf1=new RandomAccessFile("hello.txt","rw");
//中间覆盖操作
raf1.seek(3);//将指针调到角标为三的操作
// raf1.write("xx".getBytes());
//实现插入有效果
StringBuilder builder=new StringBuilder((int)new File("hello.txt").length());
byte[] buffer=new byte[20];
int len;
while((len=raf1.read(buffer))!=-1){
builder.append(new String(buffer,0,len));
}
raf1.seek(3);
raf1.write("xx".getBytes());
raf1.write(builder.toString().getBytes());
raf1.close();
}版权声明:本文为jhjhnknj原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。