> For the complete documentation index, see [llms.txt](https://brianwu.gitbook.io/brian/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://brianwu.gitbook.io/brian/java/java/file.md).

# File

當開了像是 Reader、Writer、InputStream、OutputStream 等串流，最後要記得在 finally 去關閉，不然會導致串流一直吃著，之後有要對同一個檔案修改、刪除時，就會無法正常操作。

關閉的方法，例如:

呼叫本身的關閉

`BufferedWriter.close()`

或是呼叫關閉的方法。

```
private static void close(Closeable obj) throws IOException {
    if (obj != null) {
        obj.close();
    }
}
```

## 倘若需要刪除時，檔案卻被莫名咬住，需要強行刪除

參考資料:(<https://www.itread01.com/p/819719.html>)

這種方法也只對被java程式佔用的檔案有用,對於被其他進行佔用的檔案就無能為力了

```
public boolean forceDelete(File file) {
    boolean result = file.delete();
    int tryCount = 0;
    while (!result && tryCount++ < 10) {
        System.gc(); //回收資源
        result = file.delete();
    }
    return result;
}
```
