JAVA#RandomAccessFile‘’札记
public class TESTRandomAccess {
@Test
public void mm() {
try {
RandomAccessFile rf1 = new RandomAccessFile(new File("C:\\Users\\Administrator\\IdeaProjects\\untitled\\kkkbbb.txt"), "r");
RandomAccessFile rf2 = new RandomAccessFile(new File("C:\\Users\\Administrator\\IdeaProjects\\untitled\\kkkbbb.txt"), "rw");
byte[] b = new byte[10];
int length;
while ((length = rf1.read(b)) != -1) {
rf2.write(b, 0, length);
}
rf2.close();
rf1.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void gg() {//覆盖效果
try {
RandomAccessFile rf3 = new RandomAccessFile(new File("C:\\Users\\Administrator\\IdeaProjects\\untitled\\kkkbbb.txt"), "rw");
rf3.seek(3);//seek方法,在第几位开始写;
rf3.write("i love kobe".getBytes());
rf3.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void ggg(){//insert
try {
RandomAccessFile rf4 = new RandomAccessFile(new File("C:\\Users\\Administrator\\IdeaProjects\\untitled\\kkkbbb.txt"), "rw");
rf4.seek(4);//seek方法,调整到第几位;
String str=rf4.readLine();
rf4.seek(4);
rf4.write("xy".getBytes());
rf4.write(str.getBytes());
rf4.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void gggg(){//insert
try {
RandomAccessFile rf5= new RandomAccessFile(new File("C:\\Users\\Administrator\\IdeaProjects\\untitled\\kkkbbb.txt"), "rw");
rf5.seek(4);//seek方法,调整到第几位,在其后进行操作;
byte[] b=new byte[10];
int length;
StringBuffer sb=new StringBuffer();
while((length=rf5.read(b))!=-1){
sb.append(new String(b,0,length));
}
rf5.seek(4);
rf5.write("aisong".getBytes());
rf5.write(sb.toString().getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}
}