Java简单更新方法



所以我有这样的简单方法可以下载和替换文件:

public void checkForUpdates() {
    try {
        URL website = new URL(downloadFrom);
        ReadableByteChannel rbc = Channels.newChannel(website.openStream());
        FileOutputStream fos = new FileOutputStream(downloadTo);
        fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
        fos.close();
        rbc.close();
    } catch (IOException e) {
        System.out.println("No files found");
    }
}

如何检查是否有一个具体文件,该文件位于目的地(下载)中的某个名称?现在,如果没有文件,它将下载HTML页面。

您可以从header

获得内容类型
URL url = new URL(urlname);
HttpURLConnection connection = (HttpURLConnection)  url.openConnection();
connection.setRequestMethod("HEAD");
connection.connect();
String contentType = connection.getContentType();

然后检查它是html/text或文件。

我建议检查代码200的HTTP代码。

public class DownloadCheck {
    public static void main(String[] args) throws IOException {
        System.out.println(hasDownload("http://www.google.com"));
        System.out.println(hasDownload("http://www.google.com/bananas"));
    }
    private static boolean hasDownload(String downloadFrom) throws IOException {
        URL website = new URL(downloadFrom);
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) website.openConnection();
            return connection.getResponseCode() == 200; // You could check other codes though
        }
        catch (Exception e) {
            Logger.getLogger(OffersUrlChecker.class.getName()).log(Level.SEVERE,
                    String.format("Could not read from %s", downloadFrom), e);
            return false;
        }
        finally {
            if (connection != null) {
                connection.disconnect(); // Make sure you close the sockets
            }
        }
    }
}

如果运行此代码,您将获得:

true
false

作为输出。

您可以考虑考虑其他代码200以外的其他代码。在此处查看有关HTTP代码的更多信息。

最新更新