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

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

我在最后几个小时尝试使用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(); } 

你可以直接覆盖文件。 或做以下

  1. 使用diff名称在同一目录中创建文件

  2. 删除旧文件

  3. 重命名新文件

  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}