package com.chenyang.nse.bussiness.tools.dmp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;

public class writeanywhere {
   public static void main(String[] args) {
      try {
         insert("e:/dym/threadwrite/target.txt", 5L, "插入的内容");
      } catch (IOException e) {
         e.printStackTrace();
      }

   }

   public static void create(File file, long length, String print) {
      long start = System.currentTimeMillis();

      try {
         RandomAccessFile r = new RandomAccessFile(file, "rw");
         r.setLength(length);
      } catch (Exception e) {
         e.printStackTrace();
      }

      long end = System.currentTimeMillis();
      System.out.println("create file :" + file);
      System.out.println("file length :" + print);
      System.out.println("run time : " + (end - start) + "ms");
   }

   private static void insert(String fileName, long pos, String content) throws IOException {
      File tempFile = File.createTempFile("e:/dym/threadwrite/temp", (String)null);
      tempFile.deleteOnExit();
      FileOutputStream fos = new FileOutputStream(tempFile);
      RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
      raf.seek(pos);
      byte[] buffer = new byte[4];
      int num = 0;

      while(-1 != (num = raf.read(buffer))) {
         fos.write(buffer, 0, num);
      }

      raf.seek(pos);
      raf.write(content.getBytes());
      FileInputStream fis = new FileInputStream(tempFile);

      while(-1 != (num = fis.read(buffer))) {
         raf.write(buffer, 0, num);
      }

      fos.close();
      raf.close();
      fis.close();
   }
}
