Hello

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:

try
{
	fW = new BufferedWriter(new FileWriter("Pedidos_Formacao.txt"));
	fW.write("Pedido");
	fW.newLine();
        fW.close;
}

and this is for the object file:

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

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

João

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.

http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html

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

Jump to Post

All 4 Replies

Hello,

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.