问题
I am trying to download and save the file to sd card. The file url is as follows
http://test.com/net/Webexecute.aspx?fileId=120
This url provides a stream of data. I have the following option to read the input stream.
Use generic input and output stream (no handlers for connection fail overs)
Download manager
Using HttpUrlConnection (possible timeout chances)
I have done the download using option a. But there are no handlers for connection fail overs. So I decided to go with option b
DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Request request = new Request(Uri.parse("http://test.com/net/Webexecute.aspx?fileId="+ fileId));
request.setMimeType("application/pdf");
request.setDescription("fileDownload");
request.setTitle(fileName);
request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
dm.enqueue(request);
It is downloading the file. However, the file seems to be corrupted.
While doing the research, I never found DownloadManager being used to fetch an input stream and save that to a file. Is there anything I am lacking?
回答1:
Please change your code to download a file.
protected Void downLoadFile(String fileURL) {
int count;
try
{
URL url = new URL(fileURL);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
InputStream is = url.openStream();
File testDirectory = new File(Environment.getExternalStorageDirectory() + "/Download");
if (!testDirectory.exists())
{
testDirectory.mkdir();
}
FileOutputStream fos = new FileOutputStream(testDirectory + "/filename.txt");
byte data[] = new byte[1024];
long total = 0;
int progress = 0;
while ((count = is.read(data)) != -1)
{
total += count;
int progress_temp = (int) total * 100 / lenghtOfFile;
fos.write(data, 0, count);
}
is.close();
fos.close();
readStringFromFile(testDirectory);
}
catch (Exception e)
{
Log.e("ERROR DOWNLOADING", "Unable to download" + e.getMessage());
e.printStackTrace();
}
return null;
The Below method is used to read string from file.
public String readStringFromFile(File file){
String response="";
try
{
FileInputStream fileInputStream= new FileInputStream(file+"/filename.txt");
StringBuilder builder = new StringBuilder();
int ch;
while((ch = fileInputStream.read()) != -1){
builder.append((char)ch);
}
response = builder.toString();
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
Let me know of you still face any issue..
Thanks
来源:https://stackoverflow.com/questions/24137071/read-an-inputstream-and-download-using-downloadmanager