Java:创建临时文件并替换为原始文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9887520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: create temp file and replace with original
提问by Popokoko
i need some help with creating file
我需要一些创建文件的帮助
Im trying in the last hours to work with RandomAccessFile and try to achieve the next logic:
我在最后几个小时尝试使用 RandomAccessFile 并尝试实现下一个逻辑:
- 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).
- 获取文件对象
- 创建一个具有相似名称的临时文件(我如何确保临时文件将与给定的原始文件在同一位置创建?)
- 写入此文件
- 用临时文件替换磁盘上的原始文件(应为原始文件名)。
I look for a simple code who does that preferring with RandomAccessFile I just don't how to solve these few steps right..
我寻找一个简单的代码谁更喜欢使用 RandomAccessFile 我只是不知道如何正确解决这几个步骤..
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();
}
采纳答案by Nirmal- thInk beYond
you can direct overwrite file. or do following
你可以直接覆盖文件。或做以下
create file in same directory with diff name
delete old file
rename new file
在同一目录中创建具有差异名称的文件
删除旧文件
重命名新文件
回答by jags
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}