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

时间:2017-12-02 09:19:46

标签: java filewriter bufferedwriter

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

1 个答案:

答案 0 :(得分:0)

这不是100%的解决方案,但我认为它会为您提供正确的方向。我不想100%为你工作:)

在我的评论中,我说

  1. 阅读文件内容
  2. 将其存储在变量
  3. 删除档案
  4. 从变量
  5. 中删除医生
  6. 将变量写入新文件
  7. 所以,要阅读文件内容,我们会使用一些文件(如果它是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();