請問我可以如何刪除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中的文件內容中刪除空字符
- 2. 如何在java中刪除文件的內容?
- 3. 如何通過java中的內容刪除excel文件
- 4. Java - 刪除文件夾及其內容
- 5. java FileWriter,定期刪除文件內容
- 6. Java如何讀取和刪除文件的內容。
- 7. zsh:如何刪除文件夾中的內容而不刪除文件夾?
- 8. 如何清除/刪除matlab中的.txt文件的內容
- 9. 如何刪除文件的內容而不刪除它自己?
- 10. 如何刪除phonegap中的文本文件的內容?
- 11. Node.js /刪除文件中的內容
- 12. 在Tcl中刪除文件的內容
- 13. 刪除文件中的所有內容
- 14. 在java中讀取文件時刪除的內容
- 15. 刪除舊Java文件中的SVN內容
- 16. 如何刪除mainBundle中的.txt文件的內容
- 17. 從文本部件中刪除內容
- 18. 如何刪除Java中的文件(Android)
- 19. 如何刪除Python中文件夾的內容?
- 20. 如何同時讀取和刪除文件中的內容C
- 21. 如何用Ruby-Rails刪除文件夾中的所有內容?
- 22. 如何根據ubuntu中的內容刪除多個文件
- 23. 如何使用bash腳本刪除文件夾中的內容?
- 24. 如何從C++主體中刪除文件的內容
- 25. 如何刪除SVN中文件夾的內容
- 26. 如何刪除c#中文件的內容?
- 27. 只刪除兩個子文件夾的內容
- 28. 如何刪除文本文件的內容而不刪除自己
- 29. 刪除臨時文件夾的內容
- 30. 刪除臨時文件夾的內容
你的意思是,「對寫開放的文件,_close_它」長? – 2010-04-12 13:05:31