注:所有异常都应该try-catch-finally
package com.cskaoyan.javase.homework.IOTest; import java.io.*; /**," * @author looper * @ **/ public class RAFTest2 { public static void main(String[] args) throws IOException { //找到文件位置并且接入流 RandomAccessFile raf1 = new RandomAccessFile(new File("hello.txt"),"rw"); //读文件 StringBuilder stringBuilder = new StringBuilder(); raf1.seek(4); int len; byte[] bytes = new byte[20]; while ((len=raf1.read(bytes))!=-1){ String string = new String(bytes,0,len); stringBuilder.append(string); } //只能写入字节byte,所以每次写入都要强转一下 raf1.write("什么".getBytes()); raf1.write(stringBuilder.toString().getBytes()); raf1.close(); } }
package com.cskaoyan.javase.homework.IOTest; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; /** * @author looper * @ **/ public class RandomAccessFileTest { public static void main(String[] args) throws IOException { //1.得到文件的地址 RandomAccessFile raf1 = new RandomAccessFile(new File("hello.txt"), "rw"); // RandomAccessFile raf2 = new RandomAccessFile(new File("hello1.txt"), "rw"); int len; StringBuilder s1 = new StringBuilder(); raf1.seek(3); //2.定义一个数组进行搬运 byte[] bytes = new byte[10]; //3.读的字节到最后会等于-1 ,此时已经读了存在内存里,下一步就写入 while ((len = raf1.read(bytes)) != -1) { s1.append(new String(bytes, 0, len)); } raf1.seek(3); raf1.write("123".getBytes()); raf1.write(s1.toString().getBytes()); //4.关闭流 raf1.close(); // raf2.close(); } }