請問我可以如何刪除java中的文件內容? 在此先感謝。如何只刪除java中文件的內容?
7
A
回答
13
如何:
new RandomAccessFile(fileName).setLength(0);
1
打開文件進行寫入並保存。它刪除文件的內容。
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();
}
+0
嗨, 感謝您的回覆。是否有任何方法可以部分刪除文件內容意味着從特定偏移量開始計數並刪除? – 2010-04-12 13:11:34
3
new FileOutputStream(file, false).close();
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);
}
}
0
try {
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.flush();
writer.close();
}catch (Exception e)
{
}
此代碼將刪除「文件」的當前內容,並設置文件爲0
相關問題
- 1. java FileWriter,定期刪除文件內容
- 2. 如何使用Java代碼刪除日誌文件的內容
- 3. Java如何讀取和刪除文件的內容。
- 4. 如何清除/刪除matlab中的.txt文件的內容
- 5. 如何刪除文件的內容而不刪除它自己?
- 6. 刪除文件中的所有內容
- 7. 刪除舊Java文件中的SVN內容
- 8. 在java中讀取文件時刪除的內容
- 9. 如何刪除mainBundle中的.txt文件的內容
- 10. 只刪除兩個子文件夾的內容
- 11. 如何根據ubuntu中的內容刪除多個文件
- 12. 如何刪除Python中文件夾的內容?
- 13. 如何從C++主體中刪除文件的內容
- 14. 如何使用bash腳本刪除文件夾中的內容?
- 15. 刪除所有文件夾的內容
- 16. 刪除vb.net中的文件刪除壓縮文件夾的內容
- 17. 刪除文件夾內容並從版本控制中刪除
- 18. 如何從多個JSON文件中刪除重複內容?
- 19. 刪除內容並顯示JAVA中的所有內容
- 20. Java中的文件刪除
- 21. Android:刪除文件導致內容uri
- 22. 如何刪除只讀文件?
- 23. 如何使用PHP刪除文件夾的內容?
- 24. Maven - 如何在清理階段刪除文件夾的內容?
- 25. 如何從div中刪除內容?
- 26. 如何從CALayer中刪除內容?
- 27. 如何清除文件的內容
- 28. 從c中的文本文件中刪除一些內容#
- 29. 從郵件中刪除的內容()
- 30. 如何在Python中擦除文本文件的文件內容?
你的意思是,「對寫開放的文件,_close_它」長? – 2010-04-12 13:05:31