Java:创建临时文件并用原来的替换 [英] Java: create temp file and replace with original
问题描述
我需要一些帮助来创建文件
我试着在最后几个小时使用RandomAccessFile并尝试实现下一个逻辑:
- 获取文件对象
- 创建一个类似名称的临时文件(我如何确保临时文件将被创建)
- 写入此文件
- 使用临时文件替换磁盘上的原始文件(应位于原始文件名)。
我寻找一个简单的代码谁喜欢与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-
使用diff名称在同一目录中创建文件
-
删除旧文件
-
重新命名新文件
- getting a file object
- 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?)
- write to this file
- replace the original file on the disk with the temporary one (should be in original filename).
create file in same directory with diff name
delete old file
rename new file
i need some help with creating file
Im trying in the last hours to work with RandomAccessFile and try to achieve the next logic:
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
这篇关于Java:创建临时文件并用原来的替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
-