Java: create temp file and replace with original

前端 未结 2 1245
小鲜肉
小鲜肉 2021-01-14 13:57

i need some help with creating file

Im trying in the last hours to work with RandomAccessFile and try to achieve the next logic:

  1. getting a file object
2条回答
  •  醉酒成梦
    2021-01-14 14:35

        try {
      // Create temp file.
      File temp = File.createTempFile("TempFileName", ".tmp", new File("/"));
      // Delete temp file when program exits.
      temp.deleteOnExit();
      // Write to temp file
      BufferedWriter out = new BufferedWriter(new FileWriter(temp));
      out.write("Some temp file content");
      out.close();
      // Original file
      File orig = new File("/orig.txt");
      // Copy the contents from temp to original file  
      FileChannel src = new FileInputStream(temp).getChannel();
      FileChannel dest = new FileOutputStream(orig).getChannel();
      dest.transferFrom(src, 0, src.size());
    
      } catch (IOException e) { // Handle exceptions here}
    

提交回复
热议问题