Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace first line of a text file in Java?

Tags:

java

Every time I implement the addVet method i need to replace the first line of the text file to include the number of objects. Here is my addVet method:

public static void addVet(Veterinarian newadd){
    Veterinarian.Vet.add(newadd); 
    try{
        try (PrintWriter write = new PrintWriter(new BufferedWriter(new FileWriter("VetList.txt",true)))) {
            write.println();
            write.print(newadd.getPetName());
            write.println();
            write.print(newadd.getBirthday());
            write.println();
            write.print(newadd.getSpecies());
            write.println();
            write.print(newadd.getBill());
            write.println();
            write.print(newadd.getOwner());
        }
    }
    catch (IOException cnw){
        System.err.println("file cannot be written into");
    }
}

I Don't know what method to use to write the file over. Here is the text file:

3
hopper
2003
kangaroo
555
Melody_harper
ketty
2009
cat
44
Kitty_katz
Spot
2005
Dog
333
Dottie_Marks

Thanks for the help

like image 281
Bryce Avatar asked Nov 23 '25 08:11

Bryce


1 Answers

The object is creating a new file if none exists, if it does then it will call it. In the write() method put what you want to writ in the txt file. The close() method just signifies the end of writing on the file.

FileOutputStream object=new FileOutputStream("file.txt",true);
object.write(byte[]);
object.close();
like image 123
DavidGilly Avatar answered Nov 24 '25 22:11

DavidGilly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!