[英]Deleting and Renaming file java
我正在尝试删除和重命名文件,但是 delete() 和 rename() function 不起作用。 我似乎无法在代码中找到错误,因为它应该按逻辑正确运行(我认为)。 谁能告诉我为什么它不能删除填充。 此代码有效,除了删除旧 txt 并将 temp.txt 重命名为旧文件。
public Boolean deleteItem(String item){
try{
// creating and opening file
File f = new File("temp.txt");
f.delete(); // to delete existing data inside file;
File old = new File(file);
FileWriter writer = new FileWriter(new File("temp.txt"), true);
FileReader fr = new FileReader(old);
BufferedReader reader = new BufferedReader(fr);
String s;
// creating temporary item object
String[] strArr;
//searching for data inside the file
while ((s = reader.readLine()) != null){
strArr = s.split("\\'");
if (!strArr[0].equals(item)){
writer.append(s + System.getProperty("line.separator"));
}
}
//rename old file to file.txt
old.delete();
boolean successful = f.renameTo(new File(file));
writer.flush();
writer.close();
fr.close();
reader.close();
return successful;
}
catch(Exception e){ e.printStackTrace();}
return false;
}
逻辑似乎有点混乱。 这就是我认为的样子。
你删除 file.txt
您创建一个新的 file.txt 并将“文件”复制到其中
你删除'文件'
您将 file.txt 重命名为“文件”
您关闭输入和 output 文件
我的猜测是您的操作系统(未指定)正在阻止删除和重命名打开的文件。 将关闭移动到删除/重命名之前。 并检查这些函数的返回。
另外:作为可读性的一个小改进,您不需要继续使用相同的 xxx 调用“new File(xxx)”。 文件只是文件名的表示。 做一次。 并且 'File tempFile = new File("file.txt")' 比将其称为 'f' 更容易理解。
不要使用旧的java.io.File
。 它因其松散的错误处理和无用的错误消息而臭名昭著。 使用“较新”的 NIO.2 java.nio.file.Path
和java.nio.file.Files
方法在 ZD52387880E1EA22817A72D375Z213 中添加
例如,如果文件未被删除, file.delete()
方法将返回false
。 不会抛出异常,所以你永远不会知道为什么,而且由于你甚至不检查返回值,你也不知道它也没有删除文件。
该文件没有被删除,因为您仍然打开它。 在尝试删除+重命名之前关闭文件,并使用try-with-resources执行此操作,也在Java 7 中添加。
您的代码应如下所示,通过捕获异常并将它们转换为boolean
返回值容易出错(请参阅file.delete()
的问题)。
public boolean deleteItem(String item){
try {
// creating and opening file
Path tempFile = Paths.get("temp.txt");
Files.deleteIfExists(tempFile); // Throws exception if delete failed
Path oldFile = Paths.get(file);
try ( BufferedWriter writer = Files.newBufferedWriter(tempFile);
BufferedReader reader = Files.newBufferedReader(oldFile); ) {
//searching for data inside the file
for (String line; (line = reader.readLine()) != null; ) {
String[] strArr = line.split("\\'");
if (! strArr[0].equals(item)){
writer.append(line + System.lineSeparator());
}
}
} // Files are flushed and closed here
// replace file with temp file
Files.delete(oldFile); // Throws exception if delete failed
Files.move(tempFile, oldFile); // Throws exception if rename failed
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
基本上,您想从文本文件中删除选定的行。
以下代码使用stream API 1 。 它过滤掉所有不需要的行并将您想要的行写入临时文件。 然后它将临时文件重命名为原始文件,从而有效地从原始文件中删除不需要的行。 请注意,我假设您的“全局”变量file
是一个字符串。
/* Following imports required.
import java.io.File
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
*/
Path path = Paths.get(file);
final PrintWriter[] pws = new PrintWriter[1];
try {
File tempFile = File.createTempFile("temp", ".txt");
tempFile.deleteOnExit();
pws[0] = new PrintWriter(tempFile);
Files.lines(path)
.filter(l -> !item.equals(l.split("'")[0]))
.forEach(l -> pws[0].println(l));
pws[0].flush();
pws[0].close();
Files.move(tempFile.toPath(), path, StandardCopyOption.REPLACE_EXISTING);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
finally {
if (pws[0] != null) {
pws[0].close();
}
}
1 Stream API 引入 Java 8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.