` /** * 文件中追加文字 * param fileName * param pos * paraminsertContent * throws IOException / @SuppressWarnings("resource") public static void fileAppend(String filePath, String insertContent) throws IOException { RandomAccessFile raf = null; File tmp = File.createTempFile("tmp", null); FileOutputStream tmpOut; FileInputStream tmpIn; long pointer = 0; tmp.deleteOnExit(); try { raf = new RandomAccessFile(filePath, "rw"); tmpOut = new FileOutputStream(tmp); tmpIn = new FileInputStream(tmp); //[TIMESERIES]标题占位数量 pointer = 100; pointer += getKeyIndex(filePath,"[TIMESERIES]"); // System.out.println(pointer); byte[] bbuf = new byte[64]; int hasRead = 0; raf.seek(pointer); while ((hasRead = raf.read(bbuf)) > 0) { tmpOut.write(bbuf, 0, hasRead); } raf.seek(pointer); raf.write(insertContent.getBytes()); while ((hasRead = tmpIn.read(bbuf)) > 0) { raf.write(bbuf, 0, hasRead); } } finally { raf.close(); System.out.println("file insert end!"); } } /* * 获取指定字符索引 * param srcText * param findText * return * throws IOException */ @SuppressWarnings("resource") public static long getKeyIndex(String filePath, String findText) throws IOException { long index = 0; RandomAccessFile raf = new RandomAccessFile(filePath, "rw"); String readLine = null; StringBuffer buffer = new StringBuffer(); while((readLine =raf.readLine())!=null){ buffer.append(readLine+"\r\n"); if(readLine.equals(findText)){ index = buffer.lastIndexOf(findText)+findText.length()+2; } } return index; }
`