98

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.

Leonardo Sibela
  • 1,613
  • 1
  • 18
  • 39
brig
  • 3,721
  • 12
  • 43
  • 61

17 Answers17

152

Just print an empty string into the file:

PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.close();
Vlad
  • 10,602
  • 2
  • 36
  • 38
  • 17
    The write isn't necessary, and if another task has the file open the open may not even be possible. – user207421 Dec 15 '13 at 07:13
  • writer.close??, we are in 2017!!!. Also, no need to print(""), because the text will be overwritten – FSm Feb 16 '17 at 20:11
  • 3
    @Andro, notice the timestamp and tags? Back then I remember it was the most reliable way to empty a file across Android devices. – Vlad Feb 17 '17 at 20:17
  • @Vlad If there is no need to close writer now, maybe this is a good idea to update answer? – Line Nov 03 '17 at 13:17
  • @Vlad This has never been the most reliable way, and the write is still unnecessary. It isn't reliable at all because of the swallowed exceptions, and reliable alternatives have existed since at leat 1996. – user207421 Sep 13 '21 at 08:28
  • @user207421, like I said, at that point I came across a number of Android devices and implementations that were not fully compliant with the Java SDK. Error/exception handling was never discussed and was left to the user of the snippet. – Vlad Sep 13 '21 at 08:35
  • As my experience with Android nowadays is nearly zero, I'd prefer to not edit the answer but rather let other/better answers bubble up to the top. Thank you all! – Vlad Sep 13 '21 at 08:36
86

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

PrintWriter pw = new PrintWriter("filepath.txt");
pw.close();
Roshana Pitigala
  • 8,437
  • 8
  • 49
  • 80
camleng
  • 1,008
  • 9
  • 13
31

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

Burleigh Bear
  • 3,274
  • 22
  • 32
  • 5
    This is in fact the only correct answer, as it doesn't delete the file. All other answers do. – user207421 Dec 15 '13 at 07:14
  • 1
    I need this because I would like to clear the log file created by [logback-android](https://github.com/tony19/logback-android) library. If I delete the log file manually, the library is not clever enough the create it again if there is log to write until I relaunch my app. Therefore, I used this method and work. I haven't study much. Is't it the best approach? Please advice. – Yeung Dec 16 '13 at 09:14
  • funnily, I have a production issue because Intenso card class 10 freeze (and force battery reset) when I call fileOnSdCard.setLength(0) for an app installed from .apk file. Their class 4 card never showed the issue. – Poutrathor Feb 22 '16 at 11:22
19

Simple, write nothing!

FileOutputStream writer = new FileOutputStream("file.txt");
writer.write(("").getBytes());
writer.close();
getsadzeg
  • 640
  • 3
  • 9
  • 19
Micky
  • 514
  • 3
  • 19
13

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

Kröw
  • 504
  • 2
  • 13
  • 31
Michał
  • 621
  • 5
  • 9
  • +1 For not instantiating an entire file writing class, (and even worse writing to it). This should really be the accepted answer. – Kröw Jul 06 '18 at 15:54
6

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"), "")
Anver Sadhat
  • 3,074
  • 1
  • 25
  • 26
6

How about below:

File temp = new File("<your file name>");
if (temp.exists()) {
    RandomAccessFile raf = new RandomAccessFile(temp, "rw");
    raf.setLength(0);
}
Tom
  • 16,842
  • 17
  • 45
  • 54
Sanjay Singh
  • 957
  • 10
  • 8
5

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

Rasel
  • 15,499
  • 6
  • 40
  • 50
4

Just write:

FileOutputStream writer = new FileOutputStream("file.txt");
Manh Vu
  • 131
  • 1
  • 6
2

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();
MarkoPaulo
  • 474
  • 4
  • 19
2

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.

hakon
  • 354
  • 2
  • 5
0

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

harsha
  • 61
  • 7
0

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

-1

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.

Revanth Kumar
  • 809
  • 12
  • 18
-1
FileOutputStream fos = openFileOutput("/*file name like --> one.txt*/", MODE_PRIVATE);
FileWriter fw = new FileWriter(fos.getFD());
fw.write("");
Saca
  • 10,355
  • 1
  • 34
  • 47
-1

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
Bartek
  • 45
  • 1
-2

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;
}
techGaurdian
  • 732
  • 1
  • 14
  • 35
Vishal
  • 816
  • 11
  • 19