我試圖用AsyncTask下載文件,並且下載的所有文件都有0b。我不知道該怎麼辦。有人可以幫忙嗎?請幫助我,我花了整整一天的時間。我的錯誤在哪裏?我從來沒有使用過AsyncTask,我用例子編寫了這段代碼。AsyncTask用0B下載的文件
一些代碼:
public class DownloadProgramTask extends AsyncTask<Void,Void,Void> {
int id;
MYDBHelperFromApi mydbHelperFromApi;
Program program;
List<Asana> asanaList;
public DownloadProgramTask(int id, MYDBHelperFromApi mydbHelperFromApi){
this.id = id;
this.mydbHelperFromApi = mydbHelperFromApi;
}
@Override
protected Void doInBackground(Void...params) {
program = mydbHelperFromApi.getProgramForStart(id);
asanaList = program.getAsanasList();
final String FILE_PATH_PROGRAM_VOICE = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Programs/Voice/"+id+"/";
List<String> voiceList = new ArrayList<>();
List<File> fileList = new ArrayList<>();
File dirVoice = new File(FILE_PATH_PROGRAM_VOICE);
fileList.add(dirVoice);
for (File f:fileList) {
if (!f.exists())
f.mkdirs();
}
for (Asana a:asanaList) {
File voiceFile = new File(dirVoice, a.getPose_id() + ".mp3");
if (!voiceFile.exists()) {
voiceList.add(a.getVoice());
download(MYurl.BASE_URL + a.getVoice(), voiceFile.getPath());
Log.e("LINK",MYurl.BASE_URL + a.getVoice());
Log.e("Path voice", "" + voiceFile.getPath());
}
}
return null;
}
public void download(String s, String Path_file) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(s);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.d("Something went wrong"," "+s);
}
int fileLength = connection.getContentLength();
input = connection.getInputStream();
output = new FileOutputStream(Path_file);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
if (isCancelled()) {
input.close();
}
total += count;
}
} catch (Exception e) {
Log.e("Exception", e.toString());
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
}
}
是'Log.e( 「異常」,e.toString())之前;'打印你的任何異常?我問,因爲你正在創建一個文件,然後再下載,這將解釋爲什麼你有一個0字節的文件,如果下載導致一些異常。 –