2014-09-05 153 views
1

我想清除一个文件的内容女巫有一个特定的扩展名file.tctl,我不想改变任何关于该文件的事情既不删除它。该文件是从一个特定的模型检查器生成的,这样我就可以删除内容并编写自己的内容。我想打印一个空字符串这样的:如何删除文件的内容而不删除它自己?

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

但该文件无法正常工作了。所以如果有另一种方法来清除文件的内容。

回答

-1

打电话给你的write()方法是这样的:

.write((new String()).getBytes()); 

这会让你的文件是空的。如果不工作,尝试这样的:

FileOutputStream erasor = new FileOutputStream("filename.ext"); 
erasor.write((new String()).toByteArray()); 
erasor.close(); 

或者只是尝试以覆盖该文件

//open file in override mode 
FileOutputStream out = new FileOutputStream("filename.ext"); 
//now anything that we write here will remove the old one so just write space ("") here 
+0

希望它有帮助;) – voxtor 2014-09-05 22:23:16

+0

是的,这是有帮助的:D – user3417644 2014-09-05 22:52:45

+0

第一个建议不编译:第二个是多余的。 – EJP 2014-09-06 00:05:21

-1

你必须使用一个FileOutputStream,然后你有截断()方法:

 
File f = new File("path-of-the-file.here"); 
FileChannel channel = new FileOutputStream(f, true).getChannel(); 
channel.truncate(0); 
channel.close(); 
+0

但如果我用新的文件,该文件将被删除,新的文件,具有相同的名称,将被创建。我想保留相同的文件 – user3417644 2014-09-05 22:22:10

+0

不,新文件不会在目录中创建新文件,它只会在java中创建“文件表示”。 – 2014-09-05 22:22:58

+0

删除追加模式和截断也同样适用:您不必这样做。 – EJP 2014-09-06 00:04:23

0

刚刚从你的代码完全取出打印。您已经使用新的FileOutputStream/PrintWriter /您使用的任何打开文件来截断文件。没有必要的I/O或truncate()。不要使用追加模式。

+0

你能解释一下吗?我不明白你的意思 – user3417644 2014-09-06 12:48:03

0

最简单的方法我想

new RandomAccessFile("filename.ext", "rw").setLength(0); 
相关问题