如何删除Java中的文件内容?
答案 0 :(得分:13)
这个怎么样:
new RandomAccessFile(fileName).setLength(0);
答案 1 :(得分:3)
new FileOutputStream(file, false).close();
答案 2 :(得分:1)
您可以通过打开文件for writing and then truncating its content来执行此操作,以下示例使用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:截断文件的最后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();
}
答案 3 :(得分:1)
可能问题是这只留下我认为的头而不是尾巴?
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);
}
}
答案 4 :(得分:0)
打开文件进行写入,然后保存。它删除了文件的内容。
答案 5 :(得分:-1)
try {
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.flush();
writer.close();
}catch (Exception e)
{
}
此代码将删除'file'的当前内容,并将文件长度设置为0。