Question

I wrote this method to download the latest Selenium Chrome driver, and it doesn't work. It results in a corrupt .zip file. Can anyone spot where my error is?

private final File CHROMEDRIVER = new File("chromedriver.exe");
private final File CHROMEDRIVERZIP = new File("chromedriver_win32.zip");
...
private void getLatestWindowsChromeDriver() {
  if ( !CHROMEDRIVER.exists() ) {   
    FileOutputStream fos;
    InputStream in;
    try {
      URL downloadUrl = new URL("http://chromedriver.storage.googleapis.com/index.html?path=2.8/chromedriver_win32.zip");
      URLConnection conn = downloadUrl.openConnection();
      in = conn.getInputStream();
      fos = new FileOutputStream( CHROMEDRIVERZIP.getAbsoluteFile() );
      byte[] b = new byte[1024];
      int count;
      while ( ( count = in.read(b) ) >= 0 ) {
        fos.write(b, 0, count);
      }
      fos.flush();
      fos.close();
      in.close();
    } catch ( FileNotFoundException e ) {
      e.printStackTrace();
    } catch ( IOException e ) {
      e.printStackTrace();
    } finally {
      if ( CHROMEDRIVERZIP.exists() ) {
        System.out.println( "Finished downloading Chrome driver zip archive: " + CHROMEDRIVERZIP.getAbsolutePath() );
      } else {
        System.out.println( "Failure to download the Chrome driver zip archive." );
      }             
    }
    if ( CHROMEDRIVERZIP.exists() ) {
      unzip( CHROMEDRIVERZIP.getAbsolutePath(), CHROMEDRIVER.getAbsolutePath(), "" );
      //CHROMEDRIVERZIP.delete();
    } else {
      throw new IllegalStateException( "Could not unzip Chrome driver.");
    }
  } else {
    System.out.println("Chrome driver was found located at: " + CHROMEDRIVER.getAbsolutePath() );
  }
}
Was it helpful?

Solution

Your download URL is wrong. It should be http://chromedriver.storage.googleapis.com/2.8/chromedriver_win32.zip. You are downloading the source of a web page and not a zip file. Afterwards, your code seems to work assuming that there are no bugs in the unzip method; however, I would make sure that you close the input and output streams in the finally block. I would also change the loop condition to != -1 instead of >= 0, or, better yet, use the Apache Commons IOUtils copy method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top