我制作了一个Android应用程序,可以从服务器下载文件并将其保存到内部存储中的目录中。首先,代码验证链接是否存在,如果链接存在,则下载文件。该文件正在下载,但是当我去文件夹并查看文件是否存在时,存在一个文件,但这不是我放在服务器上的文件。一切都在AsyncTask中运行
这是我的代码:
String fileName = "abc.pdf";
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a typical 0-100%
// progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ "/MyApp/");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// 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;
}
答案 0 :(得分:1)
一旦我也遇到了这个问题,最后我制作了一个Generic AsyncTask类,它只是从服务器下载文件并存储在本地文件夹中。在这段代码中,我总是从服务器获取mp3文件,所以我静态设置。 mp3格式。您可以根据您的要求更改此代码。
@Override
protected File doInBackground(Void... params) {
//File sdCardRoot = Environment.getExternalStorageDirectory()+"/Music";
File file = new File(Environment.getExternalStorageDirectory() + "/" + ConstansClass.FOLDERNAME);
if (!file.exists()) {
file.mkdir();
}
String filename = "YOUR LOCAL STORAGE FILE NAME TITLE";
yourDir = new File(file, filename + ".mp3");
if (yourDir.exists()) {
return yourDir;
}
String url = "YOUR FILE DOWNLOADING URL";
URL u = null;
try {
DebugLog.e("Request Url" + url);
u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(yourDir));
fos.write(buffer);
fos.flush();
fos.close();
DebugLog.d("Download Complete in On Background");
} catch (MalformedURLException e) {
sucess = false;
e.printStackTrace();
} catch (IOException e) {
sucess = false;
e.printStackTrace();
} catch (Exception e) {
sucess = false;
e.printStackTrace();
DebugLog.e("Error ::" + e.getMessage());
}
return yourDir;
}
<强>参数强>
注意强>
我希望你对我的想法很清楚。 谢谢,
最好的运气