![](/img/trans.png)
[英]How to delete specific file from folder in JAVA, without deleting the folder itself?
[英]how to delete the content of text file without deleting itself
我想將文件'A'的內容復制到文件'B'。 復制完成后,我想清除文件'A'的內容,並希望從頭開始寫。 我無法刪除文件'A',因為它與其他一些任務有關。
我能夠使用java的文件API(readLine())復制內容,但不知道如何清除文件的內容並將文件指針設置為文件的開頭。
只需在文件中打印一個空字符串:
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.close();
我不相信你甚至不得不在文件中寫一個空字符串。
PrintWriter pw = new PrintWriter("filepath.txt");
pw.close();
您需要RandomAccessFile類中的setLength()方法。
簡單,什么都不寫!
FileOutputStream writer = new FileOutputStream("file.txt");
writer.write(("").getBytes());
writer.close();
一個襯里進行截斷操作:
FileChannel.open(Paths.get("/home/user/file/to/truncate"), StandardOpenOption.WRITE).truncate(0).close();
有關Java文檔的更多信息: https : //docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html
寫吧:
FileOutputStream writer = new FileOutputStream("file.txt");
下面怎么樣:
File temp = new File("<your file name>");
if (temp.exists()) {
RandomAccessFile raf = new RandomAccessFile(temp, "rw");
raf.setLength(0);
}
從A復制到B后再次打開文件A到寫入模式,然后在其中寫入空字符串
Java的最佳伴侶之一是Apache Projects ,請參考它。 對於文件相關操作,您可以參考Commons IO項目。
下面一行代碼將幫助我們將文件清空。
FileUtils.write(new File("/your/file/path"), "")
將空字符串寫入文件,刷新並關閉。 確保文件編寫器不在追加模式下。 我認為應該這樣做。
如果您之后不需要使用編寫器,那么最短且最干凈的方法就是這樣:
new FileWriter("/path/to/your/file.txt").close();
您可以使用
FileWriter fw = new FileWriter(/*your file path*/);
PrintWriter pw = new PrintWriter(fw);
pw.write("");
pw.flush();
pw.close();
切記不要使用
FileWriter fw = new FileWriter(/*your file path*/,true);
filewriter構造函數中的true將啟用追加。
FileOutputStream fos = openFileOutput("/*file name like --> one.txt*/", MODE_PRIVATE);
FileWriter fw = new FileWriter(fos.getFD());
fw.write("");
使用try-with-resources編寫器將自動關閉:
import org.apache.commons.lang3.StringUtils;
final File file = new File("SomeFile");
try (PrintWriter writer = new PrintWriter(file)) {
writer.print(StringUtils.EMPTY);
}
// here we can be sure that writer will be closed automatically
使用:新的Java 7 NIO庫,試試吧
if(!Files.exists(filePath.getParent())) {
Files.createDirectory(filePath.getParent());
}
if(!Files.exists(filePath)) {
Files.createFile(filePath);
}
// Empty the file content
writer = Files.newBufferedWriter(filePath);
writer.write("");
writer.flush();
如果沒有創建目錄,上面的代碼檢查Directoty是否存在,檢查文件是否存在是否寫入空字符串並刷新緩沖區,最后讓編寫器指向空文件
您所要做的就是以截斷模式打開文件。 任何Java文件輸出類都會自動為您執行此操作。
你可以寫一個通用的方法(它太晚了,但下面的代碼會幫助你/其他人)
public static FileInputStream getFile(File fileImport) throws IOException {
FileInputStream fileStream = null;
try {
PrintWriter writer = new PrintWriter(fileImport);
writer.print(StringUtils.EMPTY);
fileStream = new FileInputStream(fileImport);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
writer.close();
}
return fileStream;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.