我正在编写一个程序来查找信息,并通过制作临时文件,删除原始文件,然后将temp重命名为原始文件,从文本文件中将其删除。到目前为止,我已经完成了编写程序的工作,并且在使用Windows控制台进行编译时工作正常,但是当我尝试在netbeans中运行相同的代码时,它无法工作,因为它无法删除并重命名原始文件。我正在寻找解决这个问题的方法。重命名和删除文件
这里是代码,当我编译它使用Windows控制台,但不是在NetBeans
import java.io.*;
public class rename {
public static String x="1123";
public void removeLineFromFile(String file, String lineToRemove) {
try {
File inFile = new File(file);
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + "2.tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().contains(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
rename util = new rename();
String jj;
util.removeLineFromFile("File.txt", x);
}
}
什么错误?发布你的堆栈跟踪。 –
只是我的自定义错误:无法删除文件 –
您确定该文件未被控制台应用程序使用吗?或另一个程序?所有的流都关闭了吗?因为它适用于我... –