我正在创建一个程序来从正在使用队列的arrayList中删除医生。这是第一次完美地工作,但第二次它复制文本文件中的数据。我该如何解决这个问题?
/**
*
* @throws Exception
*/
public void writeArrayListToFile() throws Exception {
String path = "src/assignment1com327ccab/DoctorRecordsFile.txt";
OutputStreamWriter os = new OutputStreamWriter(new FileOutputStream(path));
BufferedWriter br = new BufferedWriter(os);
PrintWriter out = new PrintWriter(br);
DoctorNode temp; //create a temporary doctorNode object
temp = end; //temp is equal to the end of the queue
//try this while temp is not equal to null (queue is not empty)
StringBuilder doctor = new StringBuilder();
while (temp != null) {
{
doctor.append(temp.toStringFile());
doctor.append("\n");
//temp is equal to temp.getNext doctor to get the next doctor to count
temp = temp.getNext();
}
}
System.out.println("Finished list");
System.out.println("Doctors is : " + doctor.toString());
out.println(doctor.toString());
System.out.println("Done");
br.newLine();
br.close();
}
答案 0 :(得分:0)
这不是100%的解决方案,但我认为它会为您提供正确的方向。我不想100%为你工作:)
在我的评论中,我说
所以,要阅读文件内容,我们会使用一些文件(如果它是txt
文件):
public static String read(File file) throws FileNotFoundException {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file.getAbsoluteFile()));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
if (line != null) sb.append(System.lineSeparator());
}
String everything = sb.toString();
return everything;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
此方法返回String
作为文件内容。我们可以将它存储在这样的变量中:
String fileContent = MyClass.read(new File("path to file"));
下一步是删除我们的文件。因为我们在内存中有它,并且我们不想要重复值......
file.delete();
现在我们应该从fileContent
移除我们的医生。这是基本的String
操作。我建议使用方法replace()
或replaceAll()
。
在String
操作之后,再次将fileContent
写入我们的文件。
File file = new File("the same path");
file.createNewFile();
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file, true), "UTF-8"));
out.write(fileContent);
out.flush();
out.close();