【发布时间】:2019-02-17 08:43:03
【问题描述】:
我尝试使用我找到的许多代码通过 AsyncTask 下载文件,但尚未成功。
我在 logcat 上收到错误:E/Error:: No such file or directory。
尽管正在寻找此错误的解决方案,但找不到什么缺失或错误。
这是我认为缺少/错误的 doInBackground 方法:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new DownloadJSON().execute("http://api.androidhive.info/json/movies.json");
}
protected String doInBackground(String...fileUrl) {
int count;
try {
String root = "data/data/com.example.jsonapp2";
URL url = new URL(fileUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
File fileName = new File(root+"/movies.json");
boolean existsOrNot = fileName.createNewFile(); // if file already exists will do nothing
// Output stream to write file
OutputStream output = new FileOutputStream(fileName,false);
byte data[] = new byte[1024];
System.out.println("Downloading");
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
谢谢。
不想用冗余代码轰炸。如果需要其他代码,我很乐意提供。
【问题讨论】:
-
您的网址似乎没有任何文件
-
我添加并更改了代码。希望现在什么都没有了。
-
这个答案可能会有所帮助,stackoverflow.com/questions/25785609/…
-
Log.d(TAG,existsOrNot) 您可以检查文件是否已创建(true)或未创建(false),如果未创建文件,则下面的代码将不会写入任何内容。
标签: android download android-asynctask