Android演示如何下载文件

演示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;
	}
}

步骤:

  1. 根据String类型URL得到InputStream;
  2. 创建目录、文件;
  3. 写入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;
	}
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值