-1

I'm trying to append an array of strings onto my text file but I also want to rewrite the first line each time too.

This is how I save my text (I attempted to append):

public static void saveText (String[] studentArray, String assignArray [], String fileName, int numStudents) throws IOException {
    File dumpFile = new File(fileName + ".txt");
    if (!dumpFile.exists()) {
        dumpFile.createNewFile();
    }

    FileWriter fw = new FileWriter (dumpFile, true);
    BufferedWriter bw = new BufferedWriter (fw);

    bw.write(Integer.toString((int)numStudents));
    bw.newLine();

    for (int i = 0; i < studentArray.length; i++) {
        bw.write(studentArray[i]);
        bw.write(", ");
    }

    for (int i = 0; i < assignArray.length; i++) {
        bw.write(assignArray[i]);
        bw.write(", ");
    }

    bw.close();
    System.out.println("SUCCESFULLY DUMPED FILE");

}
isaias-b
  • 2,255
  • 2
  • 25
  • 38
Milo
  • 43
  • 4
  • What is your actual problem? What do you expect to happen and what is actually happening? – Jeffrey Bosboom Jun 16 '14 at 14:06
  • My apologies, i can see how it wouldn't seem clear. I want to be able to append student and assignment information (the arrays) onto this file. However, I do not want want to append the number of students. I want it to be so that the number of students updates by replacing the old number. – Milo Jun 16 '14 at 15:02

1 Answers1

0

You need to use a RandomAccessFile if you want to insert into your file. I've never actually used this because to be perfectly honest I find it easier to rewrite the existing file.

mikea
  • 6,537
  • 19
  • 36
  • Well the thing is, I'm using the text file as a database to store and access information on students. Thanks for the answer though! I will try using RandomAccessFile. – Milo Jun 16 '14 at 14:47