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


89

我想将文件“ A”的内容复制到文件“ B”。复制完成后,我想清除文件“ A”的内容,并希望从文件开始就开始写。我无法删除文件“ A”,因为它与其他一些任务有关。

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

Answers:


134

只需在文件中打印一个空字符串:

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

14
不需要写操作,并且如果另一个任务打开了文件,则甚至不可能打开。
罗恩侯爵

writer.close ??,我们在2017年!!!另外,不需要print(“”),因为文本将被覆盖
FSm

1
@Andro,请注意时间戳和标记吗?那时我记得这是在Android设备上清空文件的最可靠方法。
弗拉德

@Vlad如果现在不需要关闭编写器,也许这是更新答案的好主意吗?
在线

70

我认为您甚至不必在文件中写入一个空字符串。

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

9
您对此是正确的。所有显示写入的答案都是错误的,或至多是多余的。
罗恩侯爵

33
怎么样new PrintWriter("filepath.txt").close();
Supuhstar 2014年

1
从Java docs引用:“如果文件存在,则它将被截断为零大小”
Pinkerton

1
但是如果文件处于追加模式该怎么办。
GURMEET SINGH

哦,我不能相信我错过了简单的答案。在截断模式下打开文件。我讨厌截断模式,以至于让我失望。

30

您需要在RandomAccessFile类中使用setLength()方法。


5
实际上,这是唯一正确的答案,因为它不会删除文件。所有其他答案都可以。
洛恩侯爵,

我需要这个,因为我想清除logback-android库创建的日志文件。如果我手动删除日志文件,则该库不够聪明,如果有日志要写入,请重新创建它,直到重新启动我的应用为止。因此,我使用了这种方法并工作。我还没学什么 这不是最好的方法吗?请指教。

有趣的是,我遇到一个生产问题,因为当我为从.apk文件安装的应用程序调用fileOnSdCard.setLength(0)时,Intenso卡类10冻结(并强制重置电池)。他们的第4类卡从未显示该问题。
Poutrathor '16



6

下面如何:

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

5

从A复制到B后,再次打开文件A进入写入模式,然后在其中写入空字符串


5

Java最佳伴侣之一是Apache Projects,请务必参考它。对于与文件相关的操作,您可以参考Commons IO项目。

下面的一行代码将帮助我们将文件清空。

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

4

写就好了:

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

2

将空字符串写入文件,刷新并关闭。确保文件编写器未处于追加模式。我认为应该可以解决问题。


2

如果您以后不需要使用编写器,那么最短最干净的方法就是这样:

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

1

使用:新的Java 7 NIO库,尝试

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

上面的代码检查Directoty是否存在(如果未创建目录),检查文件是否存在,则写入空字符串并刷新缓冲区,最后使写入器指向空文件


0

您可以使用

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

记住不要使用

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

在filewriter构造函数中为true将启用append。


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

欢迎来到SO!请使用内置的格式化工具使您的代码更易于阅读。
Michael L.

0

使用try-with-resources编写器将自动关闭:

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

0

您要做的就是在截断模式下打开文件。任何Java文件输出类都会自动为您完成此操作。


-2

您可以编写一个通用方法,因为(为时已晚,但是下面的代码将对您/其他人有所帮助)

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

5
这不会创建一个空文件,而是创建一个包含一个空字节的文件。
罗恩侯爵
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.