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

Dani AI

Generated

Good catch by and good pointers from and . For readers who land here later: the safest approach is to explicitly open in a truncating mode (so the file is replaced) and to use try-with-resources so streams are always closed. For text files prefer java.nio APIs which are clearer and less error-prone than hand-rolling FileWriter/BufferedWriter.

Example (truncate-and-write with NIO):

Path p = Paths.get("Pedidos_Formacao.txt");
try (BufferedWriter w = Files.newBufferedWriter(p, StandardCharsets.UTF_8,
        StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
    w.write("Pedido");
    w.newLine();
}

For serialized objects be aware that an ObjectOutputStream writes a stream header. Appending serialized objects across separate runs will put multiple headers into the file and makes reading fragile. If you must append, use a small subclass that suppresses the header for appended writes and only use the normal ObjectOutputStream for the very first write:

public class AppendingObjectOutputStream extends ObjectOutputStream {
    public AppendingObjectOutputStream(OutputStream out) throws IOException { super(out); }
    @Override protected void writeStreamHeader() throws IOException { /* no header when appending */ }
}

When opening the file, choose CREATE+APPEND with the appending stream, otherwise CREATE+TRUNCATE_EXISTING with a normal ObjectOutputStream.

Additional tips:

  • Prefer rewriting the file (truncate) unless you really need append semantics — it avoids header/format complexity.
  • Use try-with-resources so close/flush isn’t forgotten.
  • For safety against partial writes (crashes), write to a temp file and then move it over the target with REPLACE_EXISTING (ATOMIC_MOVE when supported).
  • When reading serialized data, catch EOFException to detect end-of-stream; keep serialVersionUID stable across versions.

This complements the thread: ’s observation on overwriting is helpful, and ’s delete suggestion is a valid alternate; the patterns above make the behavior explicit and robust.

Recommended Answers

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 developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.