第二次写入文件复制数据 JAVA

Writing to File duplicating data the second time JAVA

我正在创建一个程序,用于从使用队列的 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();
}

这不是 100% 的解决方案,但我认为它会给您正确的指导。我不想为你做 100% 的工作:)

我在评论中说

  1. 读取文件内容
  2. 将其存储在变量中
  3. 删除文件
  4. 从变量中删除医生
  5. 将变量写入新文件

因此,要读取文件内容,我们将使用以下文件(如果它是 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;
    }

此方法returnsString作为文件内容。我们可以将它存储在这样的变量中:

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();