文件下载的关键步骤:
1、建立一个URL类对象;
2、用URL类对象打开链接:openConnection();
3、获取其输入流,然后对输入流进行操作即可;
下面的代码实现了下载文本的内容和下载一个文件:
用强调的是一定要在配置文件中允许访问互联网和允许将内容写入sd卡中:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="gap.download"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="4" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".DownloadActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<!-- 访问互联网的权限 -->
<uses-permission android:name="android.permission.INTERNET"/>
<!-- 向SD卡写数据的权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>
一个Activity文件:
public class DownloadActivity extends Activity {
private Button textfile;
private Button mp3file;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textfile = (Button)findViewById(R.id.download_textfile);
mp3file = (Button)findViewById(R.id.download_mp3file);
textfile.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
HttpDownLoader downloader = new HttpDownLoader();
String result = downloader.download("http://192.168.19.10:8080/student/1.txt");
System.out.println(result);
}
});
mp3file.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
HttpDownLoader downloader = new HttpDownLoader();
downloader.downFile("http://192.168.19.10:8080/student/1.txt", "download/", "1.txt");
}
});
}
}
一个下载文件类:
package gap.common;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpDownLoader {
private URL url = null;
public String download(String urlStr) {
StringBuffer sb = new StringBuffer();
String line = null;
BufferedReader buffer = null;
try {
url = new URL(urlStr);
HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
while ((line = buffer.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
buffer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return sb.toString();
}
/**
* 该函数返回整形 -1:代表下载文件出错 0:代表下载文件成功 1:代表文件已经存在
*/
public int downFile(String urlStr, String path, String fileName) {
InputStream inputStream = null;
try {
FileUtils fileUtils = new FileUtils();
if (fileUtils.isFileExist(path + fileName)) {
return 1;
} else {
inputStream = getInputStreamFromUrl(urlStr);
File resultFile = fileUtils.write2SDFromInput(path,fileName, inputStream);
if (resultFile == null) {
return -1;
}
}
} catch (Exception e) {
e.printStackTrace();
return -1;
} finally {
try {
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return 0;
}
/**
* 根据URL得到输入流
*
* @param urlStr
* @return
* @throws MalformedURLException
* @throws IOException
*/
public InputStream getInputStreamFromUrl(String urlStr)
throws MalformedURLException, IOException {
url = new URL(urlStr);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConn.getInputStream();
return inputStream;
}
}
一个公用文件操作类:
/**
* 在SDCARD上面操作文件和目录的方法
* @author geng
*
*/
public class FileUtils {
private String SDPATH;
public FileUtils() {
//得到当前外部存储设备的目录
SDPATH = Environment.getExternalStorageDirectory() + "/";
}
public String getSDPATH() {
return SDPATH;
}
/**
* 在SD卡上创建文件
* @param fileName
* @return
* @throws IOException
*/
public File createSDFile(String fileName) throws IOException{
File file = new File(SDPATH + fileName);
file.createNewFile();
return file;
}
/**
* 在SD卡上创建目录
* @param dirName
* @return
*/
public File creatSDDir(String dirName) {
File dir = new File(SDPATH + dirName);
dir.mkdirs();
return dir;
}
/**
* 判断文件是否存在,存在返回true
* @param fileName
* @return
*/
public boolean isFileExist(String fileName){
File file = new File(SDPATH + fileName);
return file.exists();
}
/**
* 将一个InputStream里面的数据写入到SD卡上
* @param path:要写入的路径
* @param fileName:文件名
* @param input:输入流
* @return
*/
public File write2SDFromInput(String path, String fileName, InputStream input) {
File file = null;
OutputStream output = null;
try{
creatSDDir(path);
file = createSDFile(path + fileName);
output = new FileOutputStream(file);
byte buffer [] = new byte[4 * 1024];
while((input.read(buffer)) != -1){
output.write(buffer);
}
output.flush();
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
output.close();
}
catch(Exception e){
e.printStackTrace();
}
}
return file;
}
}