To clear the contents of a text file in Java, you can follow these steps:
FileWriter
class in the java.io
package.FileWriter
object to overwrite the file by passing true
as the second argument to the constructor.write
method of the FileWriter
object.close
method of the FileWriter
object.Here is an example of how you can clear a text file in Java:
refer to:lautturi.comimport java.io.FileWriter; import java.io.IOException; public class Main { public static void main(String[] args) { try { // Open the file for writing, overwriting any existing content FileWriter writer = new FileWriter("file.txt", true); // Write an empty string to the file writer.write(""); // Close the file writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
Alternatively, you can use the truncate
method of the RandomAccessFile
class to clear the contents of a file. This method takes an integer argument representing the number of bytes to keep in the file, and truncates the file to that size.
Here is an example of how you can use the truncate
method to clear a file:
import java.io.IOException; import java.io.RandomAccessFile; public class Main { public static void main(String[] args) { try { // Open the file for reading and writing RandomAccessFile file = new RandomAccessFile("file.txt", "rw"); // Truncate the file to 0 bytes file.setLength(0); // Close the file file.close(); } catch (IOException e) { e.printStackTrace(); } } }
Note that both of these approaches will overwrite the contents of the file. If you want to preserve the original contents of the file and simply add new content to the end, you can open the file in append mode by passing true
as the second argument to the FileWriter
constructor or the "rw"
argument to the RandomAccessFile
constructor.