Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)
How do I clear the contents of a file that exists already so that it can be blank when I write some other data in it. p.s. it should just clear the data already present not delete the existing file and create a new one with the same name.

2 Answers

0 votes
by (13.1k points)

You can do it like this:

public static void clearFile()

    try{

    FileWriter fw = new FileWriter("FileName", false);

    PrintWriter pw = new PrintWriter(fw, false);

    pw.flush();

    pw.close();

    fw.close();

    }catch(Exception exception){

        System.out.println("Exception have been caught");

    }

}

0 votes
by (1.9k points)

Open a file in write mode ('w'), and immediately close it. This truncates the file to zero length so its contents are gone but the file itself will remain. Here's the code in Python:

# Open that file in write mode to clear its contents

With open ('your_file.txt, 'w') as file :

pass #  It will clear the contents of the file

method:

1.Opens a file in write mode(‘w’), which deletes all contents.

2. Close the file and empty the file instantly.

3. Now, the file will be empty, awaiting whatever new data you wish to write to it.

Related questions

0 votes
0 answers
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...