在学校的项目上工作,我的工作遇到了一些问题(Android开发新手)。我需要从网址下载文件,所以我在网上看了如何做到这一点,我尝试按照教程但我遇到了问题,文件似乎被下载(我可以看到我的手机上的文件),但文件是0,00 ko。这是代码:
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
new DownloadFileFromURL().execute();
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL("https://www.google.fr/images/branding/googleg/1x/googleg_standard_color_128dp.png");
URLConnection connection = url.openConnection();
connection.connect();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
File root = new File(Environment.getExternalStorageDirectory() +"/sb/test2.png");
OutputStream output = new FileOutputStream(root);
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
}
/**
* After completing background task Dismiss the progress dialog
* **/
@Override
protected void onPostExecute(String file_url) {
}
}
}
如果有人有一些线索,那将是非常好的。感谢。