HttpURLConnection 下载文本文件

//
学习下载文件的方法:
1.从网络下载文件要在manifest文件中注册权限<uses-permission android:name="android.permission.INTERNET"/>2.把文件写入到SD卡中要在manifest文件中注册写入权限<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
3.HttpURLConnetion 为系统提供类
通过URL对象调用openConnection()方法转换为HttpURLConnetion类型,urlconn取得读取流;
url = new URL(urlStr);
HttpURLConnection urlconn = (HttpURLConnection)url.openConnection();
buffer = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
4.Environment.getExternalStorageState();得到一个SD卡里面的目录文件;
SDPATH = Environment.getExternalStorageState();
//

package com.example.download_app;

import com.example.Utils.HttpDownloader;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.app.Activity;

public class Download extends Activity {
	private Button downloadText = null;
	private Button downloadMp3 = null;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		downloadText = (Button)findViewById(R.id.downloadText);
		downloadMp3 = (Button)findViewById(R.id.downloadMp3);
		downloadText.setText(R.string.downloadText);
		downloadMp3.setText(R.string.downloadMp3);
		downloadText.setOnClickListener(new DownloadTextListener());
		downloadMp3.setOnClickListener(new DownloadFileListener());
	}
	
	class DownloadTextListener implements OnClickListener {
		public void onClick(View v) {
			class threadText extends Thread {
				public void run() {
					HttpDownloader hd = new HttpDownloader();
					String lrc = hd.download("http://learning.eng.cam.ac.uk/carl/code/minimize/minimize.m");
					System.out.println(lrc);
				}
			};
			new threadText().start();
		}
	}
	
	class DownloadFileListener implements OnClickListener {
		public void onClick(View v) {
			Thread threadfile = new Thread() {
				public void run() {
					HttpDownloader hd = new HttpDownloader();
					int result = hd.downloadFile("http://learning.eng.cam.ac.uk/carl/code/minimize/minimize.m", "/", "minimize.m");
					System.out.println(result);
				}
			};
			threadfile.start();
		}
	}
}

package com.example.Utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpDownloader {
	URL url = null;
	public String download(String urlStr) {
		StringBuffer sb = new StringBuffer();
		BufferedReader buffer = null;
		String line;
		try {
		//将下载地址传入到URL的构造参数   			 url = new URL(urlStr); 		//HttpURLConnection系统提供类,url的openConnection方法打开一个连接转为HttpURLConnection类型  			 HttpURLConnection urlconn = (HttpURLConnection)url.openConnection(); 		//urlconn得到一个读取字节流,转为字符流,再转为字符串流  			 buffer = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));		 //读取一行字符串,若不为空将sb添加一行字符串			
			 while ((line = buffer.readLine()) != null) {
				sb.append(line);
			}
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			try {
				buffer.close();
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	public int downloadFile(String urlStr, String path, String fileName) {
		InputStream input = null;
		try {
			FileUtils fileutils = new FileUtils();
			if (fileutils.isFileExist(path + fileName)) {
				return -1;
			} else {
				HttpURLConnection urlconn = (HttpURLConnection)url.openConnection();
				input = urlconn.getInputStream();
				File file = fileutils.writeSD(path, fileName, input);
				if (file == null) 
					return -1;
			}
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			try {
				input.close();
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
		return 0;
	}
}

package com.example.Utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.os.Environment;

public class FileUtils {
	private String SDPATH = null;
	//Environment.getExternalStorageState()取得一个SD目录名;
	FileUtils() {
		SDPATH = Environment.getExternalStorageState();
	}
	//创建一个文件夹名
	public File createSDDir(String fileName) {
		File file = new File(SDPATH + fileName);
		file.mkdir();
		return file;
	}
	//创建一个文件名
	public File createNewName(String fileName) throws Exception{
		File file = new File(SDPATH + fileName);
		file.createNewFile();
		return file;
	}
	public boolean isFileExist(String fileName) {
		File file = new File(SDPATH + fileName);
		return file.exists();
	}
	
	public File writeSD(String path, String fileName, InputStream input) {
		File file = null;
		OutputStream output = null;
		try {
			createSDDir(path);
			file = createNewName(path + fileName);
			output = new FileOutputStream(file);
			byte buffer[] = new byte[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;
	}
}


全部代码

package com.example.download_app;

import com.example.Utils.HttpDownloader;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.app.Activity;

public class Download extends Activity {
	private Button downloadText = null;
	private Button downloadMp3 = null;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		downloadText = (Button)findViewById(R.id.downloadText);
		downloadMp3 = (Button)findViewById(R.id.downloadMp3);
		downloadText.setText(R.string.downloadText);
		downloadMp3.setText(R.string.downloadMp3);
		downloadText.setOnClickListener(new DownloadTextListener());
		downloadMp3.setOnClickListener(new DownloadFileListener());
	}
	
	class DownloadTextListener implements OnClickListener {
		public void onClick(View v) {
			class threadText extends Thread {
				public void run() {
					HttpDownloader hd = new HttpDownloader();
					String lrc = hd.download("http://learning.eng.cam.ac.uk/carl/code/minimize/minimize.m");
					System.out.println(lrc);
				}
			};
			new threadText().start();
		}
	}
	
	class DownloadFileListener implements OnClickListener {
		public void onClick(View v) {
			Thread threadfile = new Thread() {
				public void run() {
					HttpDownloader hd = new HttpDownloader();
					int result = hd.downloadFile("http://learning.eng.cam.ac.uk/carl/code/minimize/minimize.m", "/", "minimize.m");
					System.out.println(result);
				}
			};
			threadfile.start();
		}
	}
}

package com.example.Utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpDownloader {
	URL url = null;
	public String download(String urlStr) {
		StringBuffer sb = new StringBuffer();
		BufferedReader buffer = null;
		String line;
		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) {
			e.printStackTrace();
		} finally {
			try {
				buffer.close();
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	public int downloadFile(String urlStr, String path, String fileName) {
		InputStream input = null;
		try {
			FileUtils fileutils = new FileUtils();
			if (fileutils.isFileExist(path + fileName)) {
				return -1;
			} else {
				HttpURLConnection urlconn = (HttpURLConnection)url.openConnection();
				input = urlconn.getInputStream();
				File file = fileutils.writeSD(path, fileName, input);
				if (file == null) 
					return -1;
			}
		} catch(Exception e) {
			e.printStackTrace();
		} finally {
			try {
				input.close();
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
		return 0;
	}
}

package com.example.Utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.os.Environment;

public class FileUtils {
	private String SDPATH = null;
	FileUtils() {
		SDPATH = Environment.getExternalStorageState();
	}
	public File createSDDir(String fileName) {
		File file = new File(SDPATH + fileName);
		file.mkdir();
		return file;
	}
	public File createNewName(String fileName) throws Exception{
		File file = new File(SDPATH + fileName);
		file.createNewFile();
		return file;
	}
	public boolean isFileExist(String fileName) {
		File file = new File(SDPATH + fileName);
		return file.exists();
	}
	
	public File writeSD(String path, String fileName, InputStream input) {
		File file = null;
		OutputStream output = null;
		try {
			createSDDir(path);
			file = createNewName(path + fileName);
			output = new FileOutputStream(file);
			byte buffer[] = new byte[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;
	}
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值