Java:创建临时文件并替换为原始文件

Pop*_*oko 3 java file

我需要一些创建文件的帮助

我在最后几个小时尝试使用 RandomAccessFile 并尝试实现下一个逻辑:

  1. 获取文件对象
  2. 创建一个具有相似名称的临时文件(我如何确保临时文件将与给定的原始文件在同一位置创建?)
  3. 写入此文件
  4. 用临时文件替换磁盘上的原始文件(应为原始文件名)。

我寻找一个简单的代码谁更喜欢使用 RandomAccessFile 我只是不知道如何正确解决这几个步骤..

编辑:好的,所以我附上了这部分代码,我的问题是我不明白什么应该是正确的步骤..文件没有被创建,我不知道如何进行“切换”

        File tempFile = null;
    String[] fileArray = null;
    RandomAccessFile rafTemp = null;
    try {
        fileArray = FileTools.splitFileNameAndExtension(this.file);
        tempFile = File.createTempFile(fileArray[0], "." + fileArray[1],
                this.file); // also tried in the 3rd parameter this.file.getParentFile() still not working.
        rafTemp = new RandomAccessFile(tempFile, "rw");
        rafTemp.writeBytes("temp file content");
        tempFile.renameTo(this.file);
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        rafTemp.close();
    }
Run Code Online (Sandbox Code Playgroud)

jag*_*ags 7

    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}
Run Code Online (Sandbox Code Playgroud)