我想下载不同类型的文件,并且有可能像这样的链接
我不知道文件名、类型和任何描述。那么如何获取这些信息。所以我将该文件名设为默认值?
谢谢你。
您必须使用异步任务来下载文件
调用它
String Your_Url = "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRpDmM-KiKgR-wcFtJnXUYVua-2409t5z7pjqski5wQ9pYZfOJG7nklFnc";
new downloadProcess(Your_Url, Your_Context).execute();
public downLoadProcess(String Url , Context context)
{
context.Url = Url ;
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
}
@Override
protected void onPostExecute(ArrayList<String> result)
{
super.onPostExecute(result);
}
@Override
protected ArrayList<String> doInBackground(Void... Params)
{
ArrayList<String> Data = new ArrayList<String>();
boolean flag = false;
URL url;
URLConnection conn;
int fileSize, lastSlash;
String fileName, path = null;
BufferedInputStream inStream;
BufferedOutputStream outStream;
File outFile;
FileOutputStream fileStream;
WebServiceMethods objWSMethod = new WebServiceMethods();
String downloadUrl = Url ;
try
{
url = new URL(downloadUrl);
conn = url.openConnection();
conn.setUseCaches(false);
fileSize = conn.getContentLength();
// get the filename
lastSlash = url.toString().lastIndexOf('/');
fileName = "file.bin";
if(lastSlash >=0)
{
fileName = url.toString().substring(lastSlash + 1);
}
if(fileName.equals(""))
{
fileName = "file.bin";
}
int DOWNLOAD_BUFFER_SIZE = fileSize;
// start download
inStream = new BufferedInputStream(conn.getInputStream());
path = Environment.getExternalStorageDirectory().toString() ;
File file = new File(path + "/Download");
file.mkdir();
path = Environment.getExternalStorageDirectory() + "/Download/" + fileName;
outFile = new File(path);
fileStream = new FileOutputStream(outFile);
outStream = new BufferedOutputStream(fileStream, DOWNLOAD_BUFFER_SIZE);
byte[] data = new byte[DOWNLOAD_BUFFER_SIZE];
int bytesRead = 0, totalRead = 0;
while((bytesRead = inStream.read(data, 0, data.length)) >= 0)
{
if(Check_your_Internet_is_on?)
{
outStream.write(data, 0, bytesRead);
totalRead += bytesRead;
flag = true;
}
else
{
flag = outFile.delete();
flag = false;
}
}
outStream.close();
fileStream.close();
inStream.close();
}
catch(MalformedURLException e)
{
}
catch(FileNotFoundException e)
{
}
catch(Exception e)
{
}
return Data;
}
}
希望它会帮助你..!