Java哈希检查

时间:2017-05-04 15:40:13

标签: java

由于某种原因,我无法弄清楚为什么每次都下载新的applet,即使我已经在我的计算机上有最新的应用程序(这是下载器/检查器的作用,检查哈希值,如果它过时了,它会重新下载上传到网络主机的新版本

我的下载程序类

public class Downloader {
    private static final String HASH_URL = "/current";
    private static final String DOWNLOAD_URL = ".jar";

    private LoadingFrame loadingFrame;

    public Downloader(LoadingFrame loadingFrame) {
        this.loadingFrame = loadingFrame;
    }

    private String getLatestHash() {
        loadingFrame.setLoadingText("Checking if client is up to date...");
        try (InputStream in = new URL(HASH_URL).openStream()) {
            return new String(IOUtils.toByteArray(in)).trim();
        } catch (IOException e) {
            loadingFrame.setLoadingText("Error loading client [ErrorCode: 7A]");
            throw new RuntimeException("Error loading client");
        }
    }


    public File downloadLatestPack() {
        try {
            File dir = new File(System.getProperty("user.home") + File.separator + "Project" + File.separator + "client");
            if (!dir.exists()) {
                dir.mkdirs();
            }
            loadingFrame.setLoadingText("Checking if client is up to date...");
            String latestHash = getLatestHash();
            File latest = new File(dir.getPath() + File.separator + latestHash + ".jar");

            if (!latest.exists() || !com.google.common.io.Files.hash(latest, Hashing.sha1()).toString().equals(latestHash)) {
                loadingFrame.setLoadingText("Doing some house keeping...");
                for (File f : dir.listFiles()) {
                    if (f.getName().endsWith(".jar") && !f.getName().equals(latest.getName())) {
                        f.delete();
                    }
                }
                loadingFrame.setLoadingText("Downloading latest client...");
                latest.createNewFile();
                try (InputStream in = new URL(DOWNLOAD_URL).openStream()) {
                    Files.copy(in, latest.toPath(), StandardCopyOption.REPLACE_EXISTING);
                }
            } else {
                loadingFrame.setLoadingText("Client is up to date!");
            }

            return latest;
        } catch (IOException e) {
            loadingFrame.setLoadingText("Error loading client [ErrorCode: 6B]");
            throw new RuntimeException("Error loading client");
        }
    }
}

0 个答案:

没有答案