Published on

java 匿名文件类没有关闭导致无法删除

Authors
    public void testNew(File file) throws FileNotFoundException {
        new PrintStream(file);
    }

//    @Test
    public void Bytes2File() throws IOException, InterruptedException {
        File file = new File(String.format("policy-%#x", System.currentTimeMillis()/1000L));
        PrintStream bufOut = new PrintStream(file);
        bufOut.write(new byte[]{0x56, 0x57, 0x58, 80});
        bufOut.close();
        Thread.sleep(3000);
//传入了 file对象,在函数中匿名创建了流没有关闭
        testNew(file);

// 通过 for循环调用系统gc,释放内存,等io释放后,删除文件
        for (int i = 0; i < 200 ; i++) {
            if(file.isFile() && file.exists()){
                System.gc();
                System.out.println("gc");
                file.delete();
            }
        }