Java: create temp file and replace with original

前端 未结 2 1221
小鲜肉
小鲜肉 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}
    
    0 讨论(0)
  • 2021-01-14 14:41

    you can direct overwrite file. or do following

    1. create file in same directory with diff name

    2. delete old file

    3. rename new file

    0 讨论(0)
提交回复
热议问题