演示Android下如何下载文件。先奉上代码下载地址。
分析如下:
Downloader.java
public int downloadFile(String link) {
int resultcode = -1;
String filename = null;
InputStream input = getInputStream(link);
if (input != null) {
File file = new File(link);
if (file.isDirectory()) {
file.list();
} else {
filename = file.getName();
}
if (filename != null) {
FileUtility fu = new FileUtility();
resultcode = fu.writeStreamToFile(true, true, DIR_NAME, filename,
input);
}
}
return resultcode;
}
}
步骤:
- 根据String类型URL得到InputStream;
- 创建目录、文件;
- 写入Stream。
其中文件操作类代码如下FileUtility.java:
package com.freesoft.utility;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.os.Environment;
import android.util.Log;
public class FileUtility {
private static int BUF_SIZE = 1024 * 4;
private static String TAG = "FileUtility";
private File createDir(String dirname) throws IOException {
File dir = new File(dirname);
if (dir.exists() != true)
if (dir.mkdir() != true)
throw new IOException();
return dir;
}
private File createFile(boolean deleteIfExsit, String dirname, String filename) throws IOException {
File file = new File(dirname + "/" + filename);
if (file.exists() != true) {
if (file.createNewFile() != true)
throw new IOException();
} else {
if (deleteIfExsit) {
if (!file.delete())
throw new IOException();
} else {
if (!file.createNewFile())
throw new IOException();
}
}
return file;
}
public int writeStreamToFile(boolean toSDCard, boolean deleteIfExsit,
String dirname, String filename, InputStream input) {
int resultcode = -1;
int len = 0;
if (toSDCard == true)
dirname = Environment.getExternalStorageDirectory() + "/" + dirname;
try {
createDir(dirname);
File file = createFile(deleteIfExsit, dirname, filename);
OutputStream output = new FileOutputStream(file);
byte buf[] = new byte[BUF_SIZE];
while ((len = input.read(buf)) != -1) {
output.write(buf, 0, len);
}
output.flush();
resultcode = 0;
} catch (IOException e) {
Log.v(TAG, "文件操作错误。");
e.printStackTrace();
}
return resultcode;
}
}