javaIO包提供了很多可以读写文件的类,但是如果想在文件的指定位置读写,就需要使用RandomAccessFile
public class App { public static void main(String[] args) throws IOException { { String s1 = "ggg\n"; String s2 = "ggg,hhh\n"; String fileName = "C:\\Users\\G007112\\Desktop\\test123.txt"; // update(fileName, 6, s1, s2); append(fileName, "zzzzz"); } } /** * 在文件指定位置插入内容 * * @param fileName * @param pos * @param s * @throws IOException */ public static void insert(String fileName, int pos, String s) throws IOException { File tmp = File.createTempFile("tmp", null); try { File file = new File(fileName); tmp.deleteOnExit(); try (RandomAccessFile rw = new RandomAccessFile(file, "rw")) { try (FileOutputStream tmpOut = new FileOutputStream(tmp); FileInputStream tmpIn = new FileInputStream(tmp)) { rw.seek(pos); byte[] buffer = new byte[64]; //读取指针之后的所有内容 int hasRead = 0; while ((hasRead = rw.read(buffer)) > 0) { tmpOut.write(buffer, 0, hasRead); } //重新定位指针 rw.seek(pos); rw.write(s.getBytes(StandardCharsets.UTF_8)); while ((hasRead = tmpIn.read(buffer)) > 0) { rw.write(buffer, 0, hasRead); } } } } catch (IOException e) { throw new RuntimeException(e); } } /** * 在文件指定位置替换内容 * * @param fileName * @param pos * @param s0 原字符串 * @param s1 目标字符串 * @throws IOException */ public static void update(String fileName, int pos, String s0, String s1) throws IOException { File tmp = File.createTempFile("tmp", null); try { File file = new File(fileName); tmp.deleteOnExit(); try (RandomAccessFile rw = new RandomAccessFile(file, "rw")) { try (FileOutputStream tmpOut = new FileOutputStream(tmp); FileInputStream tmpIn = new FileInputStream(tmp)) { rw.seek(pos + s0.length()); byte[] buffer = new byte[64]; //读取指针之后的所有内容 int hasRead = 0; //先把s1和s0之后的内容缓存 tmpOut.write(s1.getBytes(StandardCharsets.UTF_8), 0, s1.length()); while ((hasRead = rw.read(buffer)) > 0) { tmpOut.write(buffer, 0, hasRead); } //重新定位指针 rw.seek(pos); while ((hasRead = tmpIn.read(buffer)) > 0) { rw.write(buffer, 0, hasRead); } } } } catch (IOException e) { throw new RuntimeException(e); } } /** * 在文件末尾追加数据 * * @param fileName * @param s */ public static void append(String fileName, String s) { File file = new File(fileName); try (RandomAccessFile rf = new RandomAccessFile(file, "rw")) { long length = file.length(); rf.seek(length); rf.write(s.getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { throw new RuntimeException(e); } } }
标签:tmp,rw,String,读写,fileName,javaIO,hasRead,随机,new From: https://www.cnblogs.com/wangbin2188/p/17349331.html