我一直在尝试将“更新”、“删除”和“插入新内容”的类创建到文本文件中。“更新”和“删除”部分工作正常。“插入新内容”似乎没有做任何事情“。任何人都可以告诉我我的代码中可能出错或丢失的地方。
我没有收到任何错误报告,也没有代码错误突出显示。
如果文本文件中还没有新内容,我正在尝试将新内容写入文本文件。这可能类似于如果他\她是新用户,则将用户的详细信息输入文本文件以进行存储;如果已经注册,则不会输入新数据,但他们可以编辑或删除之前存储的详细信息。
如果有人在力所能及的地方提供帮助,我将不胜感激。
先感谢您。
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 EditDelete {
static PrintWriter pw;
static String line = null;
public static void newEntry() {
pw.println("A NEW ENTRY");
pw.flush();
}
public static 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));
pw = new PrintWriter(new FileWriter(tempFile));
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.startsWith(lineToRemove)) {
pw.println(line);
pw.flush();
} else if (line.startsWith(lineToRemove)) {
pw.println("THIS GOT CHANGED" + "\n" + "\n");
pw.flush();
} else if (!line.startsWith(lineToRemove) && !line.startsWith(lineToRemove)) {
newEntry();
}
}
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();
}
}
}