从网络上下载文件,保存至sd卡

1  文件下载工具类

public class DownloadTool {
	private URL url = null;
	
	//返回-1下载文件出错,返回0下载成功,返回1文件已经存在
	public int downFile(String urlStr,String path,String fileName){
		try {
			InputStream is = null;
			FileTool filetool = new FileTool();
			if(filetool.existSDFile(path+fileName)){
				return 1;
			}else{
				//inputStream = 上个从网络上获得的输入流
				is = getInputStreamFromUrl(urlStr);
				File resultFile = filetool.write2SDCARDFromInputSteam(path, fileName, is);
				if(resultFile==null)return -1;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	public InputStream getInputStreamFromUrl(String newUrl){
		URL url = null;
		HttpURLConnection httpURLConnection = null;
		InputStream is = null;
		try {
			url = new URL(newUrl);
			httpURLConnection = (HttpURLConnection)url.openConnection();
			is = httpURLConnection.getInputStream();
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return is;
	}
}


2 文件处理工具类

public class FileTool {
	private static String SDCARD = null;

	public static String getCurrentFileName(){
	  Date now = new Date(); 
	  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
	  String newdata = dateFormat.format( now ); 
     return newdata+".png";

	}
	public static void FileTool() {
		SDCARD = Environment.getExternalStorageDirectory() + "/";
	}

	// 创建一个目录
	public static File createSDDir(String dirName) {
		File fileDir = new File(SDCARD + dirName);
		fileDir.mkdir();
		return fileDir;
	}

	// 创建一个文件;
	public static File createSDFile(String fileName) throws IOException {
		File file = new File(SDCARD+fileName);   //注意在这里一定要加上主目录 SDCARD中,才可以,不然会找不到目录 。
		file.createNewFile();
		return file;
	}

	// 判断SD卡上的文件是不是存在;
	public static boolean existSDFile(String fileName) {
		File file = new File(SDCARD + fileName);
		return file.exists();
	}

	// 将一个流对象写入SDCARD
	public static File write2SDCARDFromInputSteam(String path, String fileName,
			InputStream is) {
		File file = null;
		OutputStream os = null;
		try {
			createSDDir(path);
			file = createSDFile(path + fileName);
			os = new FileOutputStream(file);
			byte[] buffer = new byte[4 * 1024];
			while (is.read(buffer) != -1) {
				os.write(buffer);
			}
			os.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				os.close();
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return file;
	}
	
	
 
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值