如何删除文本文件的内容而不删除本身

我要把文件 A 的内容复制到文件 B。 复制完成后,我要清除文件‘ A’的内容,并要从一开始就在上面写。 我不能删除文件‘ A’,因为它与其他任务有关。

我能够使用 java 的文件 API (readLine ())复制内容,但不知道如何清除文件内容并设置文件指针到文件的开头。

295647 次浏览

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.

Simple, write nothing!

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

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

Just print an empty string into the file:

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

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

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

Just write:

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

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

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

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

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.

How about below:

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

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

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

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

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