[java] how to delete the content of text file without deleting itself

I want to copy the content of file 'A' to file 'B'. after the copying is done I want to clear the content of file 'A' and want to write on it from its beginning. I can't delete file 'A' as it is related to some other task.

I was able to copy the content using java's file API(readLine() ), but don't know how to clear the content of file and set the file pointer to the beginning of the file.

This question is related to java android

The answer is


Just write:

FileOutputStream writer = new FileOutputStream("file.txt");

You can use

FileWriter fw = new FileWriter(/*your file path*/);
PrintWriter pw = new PrintWriter(fw);
pw.write("");
pw.flush(); 
pw.close();

Remember not to use

FileWriter fw = new FileWriter(/*your file path*/,true);

True in the filewriter constructor will enable append.


I don't believe you even have to write an empty string to the file.

PrintWriter pw = new PrintWriter("filepath.txt");
pw.close();

FileOutputStream fos = openFileOutput("/*file name like --> one.txt*/", MODE_PRIVATE);
FileWriter fw = new FileWriter(fos.getFD());
fw.write("");

After copying from A to B open file A again to write mode and then write empty string in it


you can write a generic method as (its too late but below code will help you/others)

public static FileInputStream getFile(File fileImport) throws IOException {
      FileInputStream fileStream = null;
    try {
        PrintWriter writer = new PrintWriter(fileImport);
        writer.print(StringUtils.EMPTY);
        fileStream = new FileInputStream(fileImport);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            writer.close();
        }
         return fileStream;
}

Write an empty string to the file, flush, and close. Make sure that the file writer is not in append-mode. I think that should do the trick.


With try-with-resources writer will be automatically closed:

import org.apache.commons.lang3.StringUtils;
final File file = new File("SomeFile");
try (PrintWriter writer = new PrintWriter(file))  {
    writer.print(StringUtils.EMPTY);                
}
// here we can be sure that writer will be closed automatically

One of the best companion for java is Apache Projects and please do refer to it. For file related operation you can refer to the Commons IO project.

The Below one line code will help us to make the file empty.

FileUtils.write(new File("/your/file/path"), "")

All you have to do is open file in truncate mode. Any Java file out class will automatically do that for you.


You want the setLength() method in the class RandomAccessFile.


One liner to make truncate operation:

FileChannel.open(Paths.get("/home/user/file/to/truncate"), StandardOpenOption.WRITE).truncate(0).close();

More information available at Java Documentation: https://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html


If you don't need to use the writer afterwards the shortest and cleanest way to do it would be like that:

new FileWriter("/path/to/your/file.txt").close();

Simple, write nothing!

FileOutputStream writer = new FileOutputStream("file.txt");
writer.write(("").getBytes());
writer.close();

using : New Java 7 NIO library, try

        if(!Files.exists(filePath.getParent())) {
            Files.createDirectory(filePath.getParent());
        }
        if(!Files.exists(filePath)) {
            Files.createFile(filePath);
        }
        // Empty the file content
        writer = Files.newBufferedWriter(filePath);
        writer.write("");
        writer.flush();

The above code checks if Directoty exist if not creates the directory, checks if file exists is yes it writes empty string and flushes the buffer, in the end yo get the writer pointing to empty file


How about below:

File temp = new File("<your file name>");
if (temp.exists()) {
    RandomAccessFile raf = new RandomAccessFile(temp, "rw");
    raf.setLength(0);
}