how to delete the content of text file without deleting itself

JavaAndroid

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

Just print an empty string into the file:

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

Solution 2 - Java

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

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

Solution 3 - Java

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

Solution 4 - Java

Simple, write nothing!

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

Solution 5 - Java

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

Solution 6 - Java

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"), "")

Solution 7 - Java

How about below:

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

Solution 8 - Java

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

Solution 9 - Java

Just write:

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

Solution 10 - Java

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.

Solution 11 - Java

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();

Solution 12 - Java

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

Solution 13 - Java

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

Solution 14 - Java

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.

Solution 15 - Java

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

Solution 16 - Java

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

Solution 17 - Java

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;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbrigView Question on Stackoverflow
Solution 1 - JavaVladView Answer on Stackoverflow
Solution 2 - JavacamlengView Answer on Stackoverflow
Solution 3 - JavaBurleigh BearView Answer on Stackoverflow
Solution 4 - JavaMickyView Answer on Stackoverflow
Solution 5 - JavaMichałView Answer on Stackoverflow
Solution 6 - JavaAnver SadhatView Answer on Stackoverflow
Solution 7 - JavaSanjay SinghView Answer on Stackoverflow
Solution 8 - JavaRaselView Answer on Stackoverflow
Solution 9 - JavaManh VuView Answer on Stackoverflow
Solution 10 - JavahakonView Answer on Stackoverflow
Solution 11 - JavaMarkoPauloView Answer on Stackoverflow
Solution 12 - JavaharshaView Answer on Stackoverflow
Solution 13 - Javauser9599745View Answer on Stackoverflow
Solution 14 - JavaRevanth KumarView Answer on Stackoverflow
Solution 15 - JavaHarpreet SinghView Answer on Stackoverflow
Solution 16 - JavaBartekView Answer on Stackoverflow
Solution 17 - JavaVishalView Answer on Stackoverflow