Reputation: 83
I have a text file that says:
Joan
Paul
Carren
What I would like to do is add Sean
at the top of the list in java
I have come across another question similar to this on stackoverflow, however, that answer overwrites the first name.
What i have right now is:
if (outputFile.exists()) {
try {
RandomAccessFile output = new RandomAccessFile(outputFileName, "rw");
output.seek(0);
output.write(headerComments.getBytes());
output.close();
} catch (IOException e) {
System.out.println("IO Exception");
}
}
File image: http://postimg.org/image/pu043d0kv/
Upvotes: 3
Views: 7952
Reputation: 5092
Similar question has been asked here Java. How to append text to top of file.txt but seem like not solved yet
You might want to try this:
BufferedReader read= new BufferedReader(new FileReader(yourfilename));
ArrayList list = new ArrayList();
String dataRow = read.readLine();
while (dataRow != null){
list.add(dataRow);
dataRow = read.readLine();
}
FileWriter writer = new FileWriter(yourfilename); //same as your file name above so that it will replace it
writer.append(headerComments);
for (int i = 0; i < list.size(); i++){
writer.append(System.getProperty("line.separator"));
writer.append(list.get(i));
}
writer.flush();
writer.close();
Upvotes: 0
Reputation: 14278
Create a file copy
. And supposed the original file is original
.
Sean
to file copy
.original
copy to file copy
original
Upvotes: 1