java 如何在Java中仅删除文件的内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2622206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to delete only the content of a file in Java?
提问by Santhosh Shettigar
How can I delete the content of a file in Java?
如何在Java中删除文件的内容?
回答by ZZ Coder
How about this:
这个怎么样:
new RandomAccessFile(fileName).setLength(0);
回答by Plap
new FileOutputStream(file, false).close();
回答by MistereeDevlord
May problem is this leaves only the head I think and not the tail?
可能的问题是这只留下我认为的头部而不是尾部?
public static void truncateLogFile(String logFile) {
FileChannel outChan = null;
try {
outChan = new FileOutputStream(logFile, true).getChannel();
}
catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("Warning Logfile Not Found: " + logFile);
}
try {
outChan.truncate(50);
outChan.close();
}
catch (IOException e) {
e.printStackTrace();
System.out.println("Warning Logfile IO Exception: " + logFile);
}
}
回答by Vlad Gudim
You could do this by opening the file for writing and then truncating its content, the following example uses NIO:
您可以通过打开文件进行写入然后截断其内容来完成此操作,以下示例使用 NIO:
import static java.nio.file.StandardOpenOption.*;
Path file = ...;
OutputStream out = null;
try {
out = new BufferedOutputStream(file.newOutputStream(TRUNCATE_EXISTING));
} catch (IOException x) {
System.err.println(x);
} finally {
if (out != null) {
out.flush();
out.close();
}
}
Another way: truncate just the last 20 bytes of the file:
另一种方法:只截断文件的最后 20 个字节:
import java.io.RandomAccessFile;
RandomAccessFile file = null;
try {
file = new RandomAccessFile ("filename.ext","rw");
// truncate 20 last bytes of filename.ext
file.setLength(file.length()-20);
} catch (IOException x) {
System.err.println(x);
} finally {
if (file != null) file.close();
}
回答by Axarydax
Open the file for writing, and save it. It delete the content of the file.
打开文件进行写入,然后保存。它删除文件的内容。
回答by Alvi
try {
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.flush();
writer.close();
}catch (Exception e)
{
}
This code will remove the current contents of 'file' and set the length of file to 0.
此代码将删除 'file' 的当前内容并将文件的长度设置为 0。

