首先是文件FileUtils.java
package mars.utils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import mars.model.Mp3Info; import android.os.Environment; public class FileUtils { private String SDCardRoot; public FileUtils() { // 得到当前外部存储设备的目录 SDCardRoot = Environment.getExternalStorageDirectory() .getAbsolutePath() + File.separator; } /** * 在SD卡上创建文件 * * @throws IOException */ public File createFileInSDCard(String fileName, String dir) throws IOException { File file = new File(SDCardRoot + dir + File.separator + fileName); System.out.println("file---->" + file); file.createNewFile(); return file; } /** * 在SD卡上创建目录 * * @param dirName */ public File creatSDDir(String dir) { File dirFile = new File(SDCardRoot + dir + File.separator); System.out.println(dirFile.mkdirs()); return dirFile; } /** * 判断SD卡上的文件夹是否存在 */ public boolean isFileExist(String fileName, String path) { File file = new File(SDCardRoot + path + File.separator + fileName); return file.exists(); } /** * 将一个InputStream里面的数据写入到SD卡中 */ public File write2SDFromInput(String path, String fileName, InputStream input) { File file = null; OutputStream output = null; try { creatSDDir(path); file = createFileInSDCard(fileName, path); 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 (Exception e) { e.printStackTrace(); } } return file; } }然后是下载的HttpDownload.java
package mars.download; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import mars.utils.FileUtils; public class HttpDownloader { private URL url = null; /** * 根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文件当中的内容 * 1.创建一个URL对象 * 2.通过URL对象,创建一个HttpURLConnection对象 * 3.得到InputStram * 4.从InputStream当中读取数据 * @param urlStr * @return */ public String download(String urlStr) { StringBuffer sb = new StringBuffer(); String line = null; BufferedReader buffer = null; try { // 创建一个URL对象 url = new URL(urlStr); // 创建一个Http连接 HttpURLConnection urlConn = (HttpURLConnection) url .openConnection(); // 使用IO流读取数据 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(); } /** * 该函数返回整形 -1:代表下载文件出错 0:代表下载文件成功 1:代表文件已经存在 */ public int downFile(String urlStr, String path, String fileName) { InputStream inputStream = null; try { FileUtils fileUtils = new FileUtils(); if (fileUtils.isFileExist(fileName,path)) { return 1; } else { inputStream = getInputStreamFromUrl(urlStr); File resultFile = fileUtils.write2SDFromInput(path,fileName, inputStream); if (resultFile == null) { return -1; } } } catch (Exception e) { e.printStackTrace(); return -1; } finally { try { inputStream.close(); } catch (Exception e) { e.printStackTrace(); } } return 0; } /** * 根据URL得到输入流 * * @param urlStr * @return * @throws MalformedURLException * @throws IOException */ public InputStream getInputStreamFromUrl(String urlStr) throws MalformedURLException, IOException { url = new URL(urlStr); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); InputStream inputStream = urlConn.getInputStream(); return inputStream; } }注意使用的时候需要添加相应的权限,还有需要开辟新的线程,以为安卓不能在主线程中执行耗时的操作(比如:下载文件)
下面是我自己写的一个,没什么技术含量,纯给新手测试用用:
package com.example.httpdownload; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; public class MainActivity extends Activity { Button downButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); downButton = (Button) findViewById(R.id.button1); if (savedInstanceState == null) { getFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment()).commit(); } downButton.setOnClickListener(listener); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /** * A placeholder fragment containing a simple view. */ public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); return rootView; } } View.OnClickListener listener = new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.button1: Thread thread = new Thread(new MyRunable()); thread.start(); break; default: break; } } }; private void downLoadFile() { String urlStr = "http://10.3.19.26:8080/2015-1-6/1.txt"; HttpDownloader httpDownloader = new HttpDownloader(); int result = httpDownloader.downFile(urlStr, "", " 1.txt"); System.out.println("<-------->" + result); } public class MyRunable implements Runnable { public void run() { // TODO Auto-generated method stub downLoadFile(); } } }