Java: create temporary file and replace with original

I need help creating a file

I've been trying for the last hours with RandomAccessFile and trying to achieve the following logic:

  • getting a file object
  • creating a temporary file with a similar name (how can I make sure the temp file will be created in the same location as the original one?)
  • write to this file
  • replace the original file on disk with a temporary one (must be in the original file name).

I'm looking for simple code that does this, preferring RandomAccessFile I just can't seem to solve these few steps correctly.

edited: Ok, so ive enclosed this piece of code my problem is that I can't figure out what the correct steps should be. no file is created and I have no idea how to make this "switch"

        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");
    } catch (IOException ex) {
    } finally {



source to share

2 answers

you can redirect the file. or do the following

  • create a file in the same directory named diff

  • delete old file

  • rename the new file



    try {
  // Create temp file.
  File temp = File.createTempFile("TempFileName", ".tmp", new File("/"));
  // Delete temp file when program exits.
  // Write to temp file
  BufferedWriter out = new BufferedWriter(new FileWriter(temp));
  out.write("Some temp file content");
  // 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}




All Articles