Java:创建临时文件并用原来的替换 [英] Java: create temp file and replace with original

查看:933
本文介绍了Java:创建临时文件并用原来的替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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


  1. 获取文件对象
  2. 创建一个类似名称的临时文件(我如何确保临时文件将被创建)

  3. 写入此文件

  4. 使用临时文件替换磁盘上的原始文件(应位于原始文件名)。


    我寻找一个简单的代码谁喜欢与RandomAccessFile
    我只是不怎么解决这几个步骤..

    编辑:
    好​​吧所以我附上这部分代码
    我的问题是,我不明白是什么应该是正确的步骤..
    文件没有被创建,我不知道该怎么做切换

      File tempFile = null; 
    String [] fileArray = null;
    RandomAccessFile rafTemp = null;
    尝试{
    fileArray = FileTools.splitFileNameAndExtension(this.file);
    tempFile = File.createTempFile(fileArray [0],。+ fileArray [1],
    this.file); //也尝试在第三个参数this.file.getParentFile()仍然不工作。
    rafTemp = new RandomAccessFile(tempFile,rw);
    rafTemp.writeBytes(temp file content);
    tempFile.renameTo(this.file);
    } catch(IOException ex){
    ex.printStackTrace();
    } finally {
    rafTemp.close();
    }


    解决方案

    您可以直接覆盖文件。或者执行以下操作:
    $ b


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


    2. 删除旧文件


    3. 重新命名新文件

    4. 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. creating a temporary file with similar name (how do i make sure the temp file will be created in same place as the given original one?)
      3. write to this file
      4. replace the original file on the disk with the temporary one (should be in original filename).

      I look for a simple code who does that preferring with RandomAccessFile I just don't how to solve these few steps right..

      edited: Okay so ive attachted this part of code my problem is that i can't understand what should be the right steps.. the file isn't being created and i don't know how to do that "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");
              tempFile.renameTo(this.file);
          } catch (IOException ex) {
              ex.printStackTrace();
          } finally {
              rafTemp.close();
          }
      

      解决方案

      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

      这篇关于Java:创建临时文件并用原来的替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆