HttpDownload下载文件以及复制到SDCard中

封装的两个工具类:

FileUtils.java
public class FileUtils {
	private String SDPATH;
	public String getSDPATH() {
		return SDPATH;
	}
	public void setSDPATH(String sDPATH) {
		SDPATH = sDPATH;
	}
	public FileUtils(){
		//得到当前外部存储设备的目录,得到的目录是/SDCARD
		SDPATH = Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator;
	}
	/**
	 * 在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 fileName
	 * @param dir
	 * @return
	 * @throws IOException
	 */
	public File createFileInSDCard(String fileName,String dir) throws IOException{
		File file = new File(SDPATH+dir+File.separator+fileName);
		file.createNewFile();
		return file;
	}
	public boolean isFileExist(String fileName){
		File file = new File(SDPATH+fileName);
		return file.exists();
	}
	/**
	 * 在SD卡上创建目录
	 * @param dirName
	 * @return
	 */
	public File createSDir(String dirName){
		File dir = new File(SDPATH+dirName);
		dir.mkdir();
		return dir;
	}
	/**
	 * 将一个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{
			createSDir(path);
			file = createSDFile(path+fileName);
			output = new FileOutputStream(file);
			byte buffer[] = new byte[4*1024];
			int temp;
			while((temp = input.read(buffer))!=-1){
				output.write(buffer,0,temp);
			}
			output.flush();
		}catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				output.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return file;
	  }

		/**
	 	* 取得目录文件名字和大小
		* FileInfo是一个实体类,存放fileName和fileSize的getter和setter方法
	 	*/
		public List<FileInfo> getFiles(String path){
			List<FileInfo> list = new ArrayList<FileInfo>();
			File file = new File(SDPATH+File.separator+path);
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++) {
				FileInfo info = new FileInfo();
				info.setFileName(files[i].getName());
				info.setFileSize(files[i].length());
				list.add(info);
			}
			return list;
		}
	}


HttpDownloader.java
public class HttpDownloader {
	private URL url = null;
	/**
	 * 下载文件,前提这个文件是文本内容
	 * @param urlStr
	 * @return
	 */
	public String download(String urlStr){
		StringBuffer sb = new StringBuffer();
		String line = null;
		BufferedReader buffer = null;
		try{
			url = new URL(urlStr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			buffer = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			while((line = buffer.readLine())!=null){
				sb.append(line);
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				buffer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
	/**
	 * 返回-1:下载出错。返回0:成功。1:已存在
	 * @param urlStr
	 * @param path
	 * @param fileName
	 * @return
	 */
	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 file = fileUtils.write2SDFromInput(path, fileName, inputStream);
				if (file == null) {
					return -1;
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			return -1;
		}finally{
			try {
				if (inputStream!=null) {
					inputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return 0;
	}
	/**
	 * 根据url得到输入流
	 * @param urlStr
	 * @return
	 * @throws IOException
	 */
	public InputStream getInputStreamFromUrl(String urlStr) throws IOException{
		url = new URL(urlStr);
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		return conn.getInputStream();
	}
}

Activity文件:
public class Download extends Activity {
    /** Called when the activity is first created. */
    @Override
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button b1 = (Button)findViewById(R.id.button1);
        b1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				HttpDownloader down = new HttpDownloader();
				String content = down.download("http://192.168.1.1:8080/abc.txt");
				System.out.println("content:"+content);
			}
		});
        Button b2 = (Button)findViewById(R.id.button2);
        b2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				HttpDownloader down = new HttpDownloader();
				int result = down.downFile("http://192.168.1.1:8080/abc.txt", "/voa", "a1.mp3");
				System.out.println("result:"+result);
			}
		});
      }
}

最后在AndroidMainfest.xml中加入访问权限
<uses-sdk android:minSdkVersion="4" />
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Download"
                  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" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

PS:最后两行将是访问权限的

你可能感兴趣的:(download)