我一直试图想出一个类,它从一个以特定数字开头的文本文件中删除一行。 我目前拥有的不显示任何代码错误,也没有错误运行;在netbeans上显示“BUILD SUCCESSFUL”,但不对该行或文本文件的任何部分执行任何操作,更不用说删除预期的行。
任何人都可以查看我的代码并告诉我我可能做错了什么,或者丢失了什么?
提前多多感谢。
继承我的代码:
package Database;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Edit {
public void removeLineFromFile(String file, String lineToRemove) {
try {
File inFile = new File("/D:/TestFile.txt/");
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() + ".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().equals(line.startsWith(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) {
Edit edit = new Edit();
edit.removeLineFromFile("/D:/TestFile.txt/", "2013001");
}
}
答案 0 :(得分:0)
将if条件更改为:
if (!line.startsWith(lineToRemove)) {
pw.println(line);
pw.flush();
}
答案 1 :(得分:0)
你的逻辑有一个问题...你是说这条线等于它自己开始的东西会永远不会发生,除非这条线只包含你要移除的线
if (!line.trim().equals(line.startsWith(lineToRemove))
我认为需要只是
if (!line.startsWith(lineToRemove))