有这样的任务:从服务器接收数据库文件(格式为.db)并覆盖新文件上的旧文件。
我试试:
@Override
public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers,
File file) {
if (statusCode != 200) {
Toast.makeText(SettingsActivity.this, getResources().getText(R.string.error),
Toast.LENGTH_SHORT).show();
return;
}
Log.v(TAG, "response - success - " + file);
try {
FileInputStream input = new FileInputStream(file);
String outputFile = String.valueOf(getApplicationContext().getDatabasePath("name_db"));
OutputStream output = new FileOutputStream(outputFile);
byte[] buffer = new byte[input.available()];
int i;
while ((i = input.read(buffer)) > 0) {
output.write(buffer, 0, i);
}
output.flush();
output.close();
input.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
pd.cancel();
}
但它不起作用。实现这个的最佳方法是什么?
以防万一,将文件发送到服务器的代码:
RequestParams params_ = new RequestParams();
AsyncHttpClient client = new AsyncHttpClient(true, 80, 443);
Context context = getApplicationContext();
File dbFile = new File(String.valueOf(context.getDatabasePath("name_db")));
try {
params_.put("db", dbFile);
} catch(FileNotFoundException e) {
Log.v(TAG, "error - file not found");
}
client.post("example.com", params_, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONObject json) {
Log.v(TAG, "response -- " + json);
try {
if (0 == json.getInt("status")) {
Toast.makeText(SettingsActivity.this, getResources().getText(R.string.successfully),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(SettingsActivity.this, getResources().getText(R.string.error),
Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
pd.cancel();
}
});