包文件; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.RandomAccessFile; / * * @describe用于操作文件中的内容 * @purpose向文件中追加内容,先指定插入点,创建临时文件,退出虚拟机 *时自动删除,把插入点之后的内容插入到临时文件中,再插入想要插入的文件,再追加临时 *文件中的内容 * * / 公共类RandomAccessFileTest { 公共静态无效的主要(字串[] args){ RandomAccessFileTest R =新RandomAccessFileTest(); 尝试{ r.insertdata(“C :/ps.txt“,52,”随笔档案2017年12月(1)“); } catch(IOException e){ // TODO自动生成的catch块 e.printStackTrace(); } } / * * @param path想要插入内容的文件路径 * @param point插入文件中的插入点位置(字节) * @param str想插入的内容 * * / public void insertdata(String path,long point,String str )抛出IOException { RandomAccessFile raf = null; File targetfile = new File(path); raf = new RandomAccessFile(targetfile,“rws”); File temp = File.createTempFile(“temp”,null); //第二个参数为null,生成的文件后缀为.tmp temp.deleteOnExit(); FileOutputStream out = new FileOutputStream(temp); FileInputStream in = new FileInputStream(temp); raf.seek(点); 字节[] b =新字节[1024]; byte [] b2 =新字节[1024]; int len = 0; 而((LEN = raf.read(B))!= - 1){ out.write(b,0,len); } raf.seek(点); raf.write(str.getBytes()); int len2 = 0; 而(((LEN2)= in.read(B2))!= - 1){ raf.write(b2,0,LEN2); } } }
RandomAccessFile
猜你喜欢
转载自blog.csdn.net/m0_37879526/article/details/80252108
今日推荐
周排行