下载URL文件(如果存在)。

时间:2014-05-11 08:15:20

标签: android file

大家好我尝试从url下载文件,如果存在...我的问题是文件下载而不存在于服务器...

如果有人帮助我,我将不胜感激......

我无法弄清楚检查文件是否存在下载它,如果不忽略...

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

}

感谢您的帮助..

2 个答案:

答案 0 :(得分:0)

使用以下代码检查您的文件是否存在于给定的网址中。

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

如果文件存在,该方法返回'true',然后下载它。 别这样说。

答案 1 :(得分:0)

如果您连接到HTTP URL,您实际上将获得HttpURLConnection对象。它有一个getResponseCode方法,可以为您提供HTTP状态代码。