Java file delete 无法删干净文件

restassured 的 filter 重写

public class ApiFilter implements Filter {
    @Override
    public Response filter(FilterableRequestSpecification filterableRequestSpecification, FilterableResponseSpecification filterableResponseSpecification, FilterContext filterContext) {
        // 修改 log 日志文件的名称生成
        String apiLogPath = TimeUtil.getFormat() + new FakerUtil().getNum(800) + ".txt";

        // 修改请求 filterableRequestSpecification
        // 添加全局参数
        filterableRequestSpecification.queryParam("access_token", AccessToken.getToken());
        try {
            RequestPrinter.print(filterableRequestSpecification,
                    filterableRequestSpecification.getMethod(),
                    filterableRequestSpecification.getURI(),
                    LogDetail.ALL,
                    logConfig().blacklistedHeaders(),
                    new PrintStream(new FileOutputStream(apiLogPath, false)),
                    true);

            // allure 报告动态添加
            FileInputStream req = new FileInputStream(apiLogPath);
            addAttachment("接口请求日志:", req);
            req.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Response responseOrigin = filterContext.next(filterableRequestSpecification, filterableResponseSpecification);

        // 响应修改
        Response responseAction = new ResponseBuilder().clone(responseOrigin).build();


        try {
            ResponsePrinter.print(responseAction,
                    responseAction.getBody(),
                    new PrintStream(new FileOutputStream(apiLogPath, false)),
                    LogDetail.ALL,true,
                    logConfig().blacklistedHeaders());

            // allure 报告动态添加
            FileInputStream res = new FileInputStream(apiLogPath);
            addAttachment("响应结果日志:", res);
            res.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


        return responseAction;
    }
}

测试类

public class BaseTest {

    @BeforeAll
    @AfterAll
    static void cleanTxt(){
        // 获取当前路径

        File file = new File(System.getProperty("user.dir"));
        File[] files = file.listFiles();
        assert files != null;

        Arrays.stream(files).filter(file1 -> file1.toString().endsWith(".txt")).collect(Collectors.toList())
                .forEach(file1 ->
                        file1.delete()
                        );
    }
}
@DisplayName("添加部门")
public class AddDepartApiFilterDemo extends BaseTest {



    @DisplayName("随机添加")
    @RepeatedTest(value = 10, name = DISPLAY_NAME_PLACEHOLDER + " " + CURRENT_REPETITION_PLACEHOLDER + "/" + TOTAL_REPETITIONS_PLACEHOLDER)
    void addDepart() {
        Response response = given().filter(new ApiFilter()).log().all()
                .contentType("application/json;charset=UTF-8")
                .body(getBodyMap())
                .when()
                .post("https://qyapi.weixin.qq.com/cgi-bin/department/create")
                .then().log().all()
                .statusCode(200)
                .extract().response();
        Integer errcode = response.path("errcode");
        String errorMessage = response.path("errmsg");
        assertAll(
                () -> assertEquals(0, errcode),
                () -> assertEquals("created", errorMessage));
    }

    private HashMap<String, Object> getBodyMap() {
        FakerUtil fakerUtil = new FakerUtil();
        MapperUtil<HashMap<String, Object>> mapper = new MapperUtil<>();
        HashMap<String, Object> readValue = mapper.getReadValue("src/test/resources/addDepart.json");
        HashMap<String, Object> depart = new HashMap<>();
        readValue.forEach(
                (s, o) -> {
                    String value = o.toString();
                    if (value.startsWith("${") && value.endsWith("}")) {
                        String s1 = StringUtils.stripStart(value, "${");
                        String s2 = StringUtils.stripEnd(s1, "}");
                        if ("departName".equals(s2)) {
                            o = fakerUtil.getName() + fakerUtil.getTimeStamp();
                        }
                        if ("orderId".equals(s2)) {
                            o = fakerUtil.getNum(1000);
                        }
                    }
                    depart.put(s, o);
                }
        );
        return depart;
    }
}

执行中后发现,Response 产生的日志文件没有办法删除干净。debug 时, ApiFilter 下的 file1.delete() 有遍历所有的txt文件。但是有部分,执行完 file1.delete() 并没有删除成功。

百度过,说是 文件删除之前文件流没有关闭。所以,我在 ApiFilter 下,加了res.close()。但依旧没有用。

请问下这个要怎么弄?

缓存问题,解决方案:delete之前添加以下代码:

System.gc();
1 Like
关闭