简体   繁体   中英

Write and read txt file

I'm trying to do project which contains patient information and print them if user want. But it is currently adding only one person. I want to add infinite information and I don't how can I fix it.

public static void saveChanges(ArrayList<Human> humans) throws IOException {
    File veritabani = new File("patients.txt");
    System.gc();
    RandomAccessFile raf = new RandomAccessFile(veritabani, "rw");
    raf.close();
    veritabani.delete();
    int ctrWhile = 0;
    for (int yazdir = 0; yazdir < humans.size(); yazdir++) {

        File f = new File("patients.txt");
        PrintWriter pw = new PrintWriter(new FileOutputStream(f, true));
        String tName=humans.get(yazdir).getNameAndSurname();
        int tID=humans.get(yazdir).getTC();
        int tAge=humans.get(yazdir).getAge();
        boolean tInsuance=humans.get(yazdir).isInsurance();
        String tComplain=humans.get(yazdir).getComplain();

        if (ctrWhile== 0) {
            pw.append(tName+"-"+tID+"-"+tAge+"-"+"-"+tInsuance+"-"+tComplain+"-");
            ctrWhile++;
        } else {
            pw.append("\n"+tName+"-"+tID+"-"+tAge+"-"+"-"+tInsuance+"-"+tComplain+"-");

        }
        pw.close();
    }
}

Each time through your loop, you appear to create a new file, write to it, and close it. Therefore each time through your loop you will overwrite the file created before.

Create the file before entering the loop, and close it after you've completed the loop; only write to it within the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM