即使不存在Android下载

时间:2014-03-12 11:35:11

标签: android

try {

    URL url = new URL("http://URL/Dragonfly.db");
    HttpURLConnection c = (HttpURLConnection) url.openConnection();
    c.setRequestMethod("GET");
    c.setDoOutput(true);
    c.connect();
    String[] path = url.getPath().split("/");
    String _file = path[path.length - 1];

    int lengthOfFile = c.getContentLength();
    if(lengthOfFile > 0){ // Copy file if Length > 0
    String PATH = db.DB_PATH; ;//Environment.getExternalStorageDirectory()+ 
    Log.v("", "PATH: " + PATH);
    File file = new File(PATH);
    file.mkdirs();

    String fileName = "Dragonfly.db";

    File outputFile = new File(file , fileName);
    FileOutputStream fos = new FileOutputStream(outputFile);

    InputStream is = c.getInputStream();

    byte[] buffer = new byte[1024];
    int len1 = 0;
    while ((len1 = is.read(buffer)) != -1) {

    fos.write(buffer, 0, len1);
    }
    fos.close();
    is.close();

    }else{
        TestAdapter mDbHelper = new TestAdapter(getBaseContext());
        mDbHelper.createDatabase();
    }
    } catch (IOException e) {
    e.printStackTrace();
    }

我使用此代码更新数据库,下载新数据库。但如果我在服务器上没有文件,它会替换我有一个新的空数据库(0字节)。

如果文件存在于服务器上,我该如何下载文件?

1 个答案:

答案 0 :(得分:0)

尝试进行状态响应检查:

int responseCode = c.getResponseCode();

if (responseCode == HttpURLConnection.HTTP_OK) {
{
    // update database replacing the old one with the new one
} else {
    // continue to use old database
}