Question

I'm writing some Strings on a text file on java. I'm new with this and I don't now much about file writing.

I achieved to write strings on a file, and read them, but I don't know how to delete the content of this file.

This is the way I write:

public void writefile(object listToWrite) throws IOException {
    fileOutPutStream = new FileOutputStream (file);
    write = new ObjectOutputStream (fileOutPutStream);
    for (int i=0; i<=listToWrite.size(); i++){
        write.writeObject(listToWrite.get(i));
    }
    counter = listToWrite.size();
    write.close();
}

And this is the way I read:

public ArrayList readfile() throws Exception, FileNotFoundException, IOException {
    ArrayList<String> objectList= new ArrayList<>();
    fileInPutStream = new FileInputStream (file);
    read = new ObjectInputStream (fileInPutStream);
    for (int i=0; i<counter; i++){
        objectList.add((String)read.readObject());
    }
    read.close();
    return objectList;
}
Was it helpful?

Solution

So you want to delete the content of a file but not the file itself?

PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.close();

Just put an empty string into the file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top