문제

Hi everyone I'm trying download file from url if exist… my problem is file downloaded without exist from server…

i will appreciate if anyone help me…

I can not figure out check if file exist download it if not ignore…

  private void startDownload() {
    // TODO Auto-generated method stub

    String url = "http://example.com/file/krs.db";
    new DownloadFileAsync().execute(url);
}

class DownloadFileAsync extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... aurl) {
        int count;

        try {
            URL url = new URL(aurl[0]);
            URLConnection conexion = url.openConnection();
            conexion.connect();

            int lenghtOfFile = conexion.getContentLength();
            Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

            // create empty directory if not exist
            File appDir = new File(sdcardBaseDir + externalPath);
            if (!appDir.exists())
                appDir.mkdirs();

            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream(sdcardBaseDir
                    + externalPath + IcsvFileName);

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {
        }
        return null;

    }

    protected void onProgressUpdate(String... progress) {
        Log.d("ANDRO_ASYNC", progress[0]);
    }

}

Appreciate your help..

도움이 되었습니까?

해결책

Use the code below to check whether your file is exist in the given url.

public static boolean exists(String URLName){
try {
  HttpURLConnection.setFollowRedirects(false);
  // note : you may also need
  //        HttpURLConnection.setInstanceFollowRedirects(false)
  HttpURLConnection con =
     (HttpURLConnection) new URL(URLName).openConnection();
  con.setRequestMethod("HEAD");
  return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
   e.printStackTrace();
   return false;
}
}

The method returns 'true' if file exists, Then download it. Ignore otherwise.

다른 팁

If you connect to a HTTP URL, you will actually get back a HttpURLConnection object. It has a getResponseCode method that gives you the HTTP status code.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top