I'm having some trouble writing to text and object files in java. Basically i need to delete the contents of the file before i write the new information on it...which i'm not being able to do.

well this is what i have in terms of code for the text file:

	fW = new BufferedWriter(new FileWriter("Pedidos_Formacao.txt"));

and this is for the object file:

	os = new ObjectOutputStream(new FileOutputStream("Utilizadores.bin"));
        User x = new User("João",1);

I have no problem writing but i need to delete the contents of the file before doing so or else this code will simply add the new information to the one that was already in the file.
Can anyone help me?

Thanks in advance


Recommended Answers

I would imagine that Puneetkay is correct since this is what I know from experience. But if you want to explicitly delete the file, use the File class.


File myFile = new File("fileName.txt");

Jump to Post

All 4 Replies


Well this code will overwrite the data in file. You don't need to delete content of files before adding new information.

Also, i just tried both codes. Working perfectly! and data in both files were overwrote.

Best of luck!

You are right...stupid mistake by me...was calling the function in the wrong place:P

Anyway thank you all:)

Mark solved threads as solved

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.