1. 普通文本类型的文件下载:根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文本中的内容,步骤如下:
A:创建一个URL对象
B:通过URL对象的openConnection()方法,得到一个HttpURLConnection对象
C:通过HttpURLConnection连接对象的getInputStream()方法得到InputStream字节流.
D:从InputStream当中读取数据
Java代码:返回文本类型文件的字符串形式。
public String DownLoadText(String urlStr) {
String resultString=null;
BufferedReader bufferedReader=null;
StringBuffer sbBuffer=new StringBuffer();
try {
//先获取URL对象;
url=new URL(urlStr);
//建立一个Http连接的对象;
HttpURLConnection httpConn=(HttpURLConnection)url.openConnection();
//使用IO流读取数据;
bufferedReader=new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
//循环输出每一行;
while ((resultString=bufferedReader.readLine())!=null) {
sbBuffer.append(resultString);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
//关闭。
bufferedReader.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return sbBuffer.toString();
}
2. 通用文件下载。
/**
* 下载通用文件,-1:代表下载出错;0:代表下载成功;1:代表文件已存在;
*/
public int downLoadFile(String urlString,String dirpath,String filepath) {
int state=0;
InputStream inputStream=null;
//得到文件操作类的对象(上节中提到的几个方法);
FileUnits units=new FileUnits();
try{
//先判断要下载的文件是否存在
if(units.checkFileExists(dirpath+filepath))
{
state=1;
}
else{
//根据Url得到InputStream字节流,此方法附下;
inputStream=getInputStreamByUrl(urlString);
//调用上节中SD卡文件操作的方法来将InputStream写入到SD中去。
File resultFile= units.writeStreamToSDCard(dirpath, filepath, inputStream);
if (resultFile==null) {
state=-1;
}
}
}
catch (Exception e) {
e.printStackTrace();
state=-1;
}
finally
{
try {
inputStream.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return state;
}
/**
* 根据url得到输入流;
* urlString 是下载链接地址
*/
public InputStream getInputStreamByUrl(String urlString) throws IOException {
url=new URL(urlString);
HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
return urlConnection.getInputStream();
}