0

So i have this simple method to download and replace a file:

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");
    }
}

How can i check if there is a concrete file with a certain name located in the destination (downloadFrom) ? Right now if there are no files it downloads the html page.

R.Ro
  • 449
  • 1
  • 7
  • 15

2 Answers2

0

You can get content type from header

URL url = new URL(urlname);
HttpURLConnection connection = (HttpURLConnection)  url.openConnection();
connection.setRequestMethod("HEAD");
connection.connect();
String contentType = connection.getContentType();

then check it's HTML/text or files.

nhoxbypass
  • 9,695
  • 11
  • 48
  • 71
0

I suggest to check the HTTP code for code 200. Something along these lines:

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
            }
        }
    }
}

If you run this code, you will get:

true
false

as the output.

You could consider to consider other code than code 200 as OK. See more information on HTTP codes here.

gil.fernandes
  • 12,978
  • 5
  • 63
  • 76