-1
 BufferedReader input = new BufferedReader (new FileReader("data.txt")); //Reading the file
 String data [] = readFile (input); //data is each line in the file
 String student [] = new String [10];
 for(int x = 0; x<data.length; x++)
  {                
   student = data[x].split(","); //each line is being split into 11 parts
  }

I need to write in this file without overwriting it. I ask 10 questions like, "What is your first name?", and "What is your last name?". I need the answers of these questions going into a student []. Like I said, I need the code to write into this file without overwriting it.

user207421
  • 305,947
  • 44
  • 307
  • 483
user3161311
  • 33
  • 1
  • 4
  • 1
    I see input in this code but no output. How are you planning on writing to a file without any output? – Tdorno Jan 14 '14 at 02:07
  • You can *append* (keyword) to a file without overwriting it. – user2864740 Jan 14 '14 at 02:11
  • I think "append" is the word you're looking for, and it requires opening the file in a particular mode and observing some restrictions about how you reference it. – Hot Licks Jan 14 '14 at 02:19

1 Answers1

2
PrintWriter out = null;
try {

out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", 

true)));
    out.println("the text");
} catch (IOException e) {
    e.printStackTrace ();
} 
finally {
  if (out != null) {
     out.close ();
  }
}

The second parameter to the FileWriter constructor will tell it to append to the file (as opposed to clearing the file).

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
  • 2
    +1 Please use `try-with-resources` or `close()` in finally, never empty catch `do some log` or something like that :) – nachokk Jan 14 '14 at 02:12
  • @nachokk You are absolutely correct and the SO code that I copied was merely pasted without alteration. I amended the answer. – Scary Wombat Jan 14 '14 at 02:36
  • 1
    *"The SO code I copied"* ... you mean like, someone else's answer, from a question this should have been flagged as a dup of? – Brian Roach Jan 14 '14 at 04:30