在不同的功能中使用相同的while循环

时间:2019-10-30 10:54:25

标签: java

我在两个不同的函数中有一个非常类似的while循环,我该如何编写两个函数使用相同while的代码?想法是,当我使用这两个功能中的任何一个时,它们应该实现放弃前重试5次的行为。

    public Document getHtml(String url) {
        int retries = 0;
        while (retries < 5) {
            try {
                return Jsoup.connect(url).get();
            } catch(IOException e) {
                LOGGER.logWarn("Problem Occured While Downloading The File= " + e.getMessage());
            }
            retries += 1;
        }
        return null;
    }

    @Override
    public String getFile(String url) {
        int retries = 0;
        while(retries < 5) {
            try {
                URL urlObj = new URL(url);
                ByteArrayOutputStream result = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int length;
                try (InputStream is = urlObj.openStream()) {
                    while ((length = is.read(buffer)) != -1) {
                        result.write(buffer, 0, length);
                    }
                }
                return result.toString("UTF-8");
            } catch (IOException e) {
                LOGGER.logWarn("Problem Occured While Downloading The File= " + e.getMessage());
            }
            retries += 1;
        }
        return null;
    }

1 个答案:

答案 0 :(得分:4)

您可以将重试逻辑提取为高阶函数:

[0-9]{1}

str_extract_all("A1BB2CCC3","[A-Z]+|[0-9]") [[1]] [1] "A" "1" "BB" "2" "CCC" "3" 在哪里:

public static <T> T retry5Times(ThrowingSupplier<T, IOException> supplier) {
    for(int i = 0; i < 5; i++) {
        try {
            return supplier.get();
        } catch (IOException e) {
            LOGGER.logWarn("Problem Occured While Downloading The File= " + e.getMessage());
        }
    }
    return null;
}

并以这种方式使用它:

ThrowingSupplier