Nathaly
Nathaly

Reputation: 83

Add line at the beginning of text file - Java

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

Answers (2)

Baby
Baby

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

Trying
Trying

Reputation: 14278

Create a file copy. And supposed the original file is original.

  • write the line Sean to file copy.
  • for each line in file original copy to file copy
  • delete the file original

Upvotes: 1

Related Questions