我正在尝试通过制作临时文件,操作文本,然后删除原始文件来替换文件的内容以用temp替换它。这是方法:
private void deleteLine(String lineToRemove){
File inputFile = new File("./src/class1.txt");
File tempFile = new File("./src/tempFile.txt");
BufferedReader reader;
reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer;
writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
while((currentLine = reader.readLine()) != null) {
if(!currentLine.trim().equals(lineToRemove)){
writer.write(currentLine + System.getProperty("line.separator"));
}
}
writer.close();
reader.close();
System.out.println("Input to temp1: " + tempFile.renameTo(inputFile));
}
在测试这个方法时,我发现一切都按预期工作,除了最后两行,它们都返回false。方法启动时我的class1.txt文件存在,但tempFile.txt没有。
答案 0 :(得分:1)
下面的代码看起来很迷人:
private static void copyFiles(File source, File dest) throws IOException {
Files.move(source.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
答案 1 :(得分:0)
你的tempFile.txt
在那里,但你没有看到它:),尝试刷新你的项目(我假设你正在使用eclipse)。
Right click
> Refresh
您将看到该文件。
您还需要inputFile.delete();
来电
writer.close();
reader.close();
inputFile.delete();
System.out.println("Input to temp1: " + tempFile.renameTo(inputFile));
答案 2 :(得分:0)
使用try-with-resources,Streams和NIO.2的工作解决方案,其中有一些benefits:
Path inputPath = Paths.get("foo.txt");
Path outputPath = Paths.get("foo.txt.tmp");
try (Stream<String> lineStream = Files.lines(inputPath);
BufferedWriter writer = Files.newBufferedWriter(outputPath)) {
lineStream
.filter(line -> !"pattern".equals(line.trim()))
.forEach(line -> {
try {
writer.append(line);
writer.newLine();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
}
Files.delete(inputPath);
Files.move(outputPath, inputPath);
答案 3 :(得分:0)
使用apache commons io进行Java复制/替换文件操作
private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
FileUtils.copyFile(source, dest);
}