2012-03-27 24 views
3

我需要一些帮助创建文件的Java:创建临时文件,以原创

替换

我试着在最后几个小时用RandomAccessFile的工作,努力实现下一个逻辑:

  1. 获取文件反对
  2. 创建具有类似名称的临时文件(我如何确保临时文件将在同一地点的原之一创建?)
  3. 写入该文件
  4. 代表将原始文件与临时文件绑定在一起(应该使用原始文件名)。

我寻找一个简单的代码谁做与RandomAccessFile的 宁愿我不如何解决这些权几步..

编辑: 好了,香港专业教育学院attachted的代码 这部分我问题是,我不明白什么应该是正确的步骤.. 不被创建的文件,我不知道该怎么做“开关”

 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(); 
    } 
+0

您有什么问题的新文件?你好吗? – Marcelo 2012-03-27 10:17:28

+0

我添加了一些代码,我不知道如何做这个开关,我想我比它更复杂。 – Popokoko 2012-03-27 10:21:47

+0

您需要检查renameTo的返回以测试它是否工作,并且您可能需要在重命名之前删除this.file文件。 – 2012-03-27 13:02:03

回答

1

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

  1. 与DIFF名称相同目录下创建文件

  2. 删除旧文件

  3. 重命名

+0

该文件没有被创建我不明白为什么.. – Popokoko 2012-03-27 10:22:50

+0

可以提供一个例子吗? – Popokoko 2012-03-27 10:49:59

4
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

谢谢,但即时通讯不是很确定它填充我所需要的,这个临时文件创建不会创建原始位置(这是动态的..我不能写作“/”作为根),第二个transferFrom方法的复制方法是有点问题,因为我有很多内容“移动”,这就是为什么在一些工作方式重命名可能是更好的想法.. – Popokoko 2012-03-27 10:48:59

+1

这应该有助于解决您的问题。 File tempFile = null; RandomAccessFile rafTemp = null; 尝试tempFile = File.createTempFile(“TempFile”,“.tmp”); rafTemp = new RandomAccessFile(tempFile,“rw”); rafTemp.writeBytes(“temp file content”); tempFile.renameTo(new File(“/ destinationpath/dest.txt”)); catch(IOException ex){ ex.printStackTrace(); } finally { rafTemp.close(); } – jags 2012-03-27 11:19:34

+0

呃,我已经试过了,仍然没有工作:/要么我错过了什么或逻辑是不正确的。顺便说一句,我仍然需要支持一个给定的文件synamid和你的代码实现静态路径的事实.. – Popokoko 2012-03-27 11:28:52