个人开发,如果有什么错误或是各位高手有更好的实现方法请不吝赐教,这厢表示强烈感谢
文件下载步骤:
创建一个HttpURLConnection对象 HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
获得一个输入流InputStream对象 urlConn.getInputStream()
访问网络权限 android.permission.INTERNET (允许程序访问网络)写入AndroidManifest.xml 的<uses-permission android:name="" />标签内
如果要访问SD,要再加入访问SD卡的权限:android.permission.WRITE_EXTERNAL_STORAGE
访问SDCARD
得到当前SD卡的目录:
Environment.getExternalStorageDirectory()
完整工具类代码:
HttpDownloader.java
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; public class HttpDownloader { private URL url; public static final int FILEEXIST = 1;//文件已经存在 public static final int DOWNLOADFAIL = -1;//文件下载失败 public static final int DOWNLOADSUCCESS = 0;//文件下载成功 /** * 下载 text文本文件 * @param urlStr * @return */ public String download(String urlStr){ StringBuffer sb = new StringBuffer(""); String line = null; BufferedReader buffer = null; 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 + "\n"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return ""; }finally{ try { buffer.close(); } catch (Exception e) { return sb.toString(); } } return sb.toString(); } /** * 下载文件,原文件名默认为原文件名 * @param urlStr 现在的文件的链接 * @param path 下载的文件存放到SD的目录 * @param cover 当文件存在时是否覆盖,true覆盖 * @return */ public int download(String urlStr, String path, boolean cover){ File oldFile = new File(urlStr); return download(urlStr, path, oldFile.getName(), cover); } /** * 下载文件 * @param urlStr 现在的文件的链接 * @param path 下载的文件存放到SD的目录 * @param fileName 文件名 * @param cover 当文件存在时是否覆盖,true覆盖 * @return */ public int download(String urlStr, String path, String fileName, boolean cover){ InputStream inputStream = null; if(FileUtils.isFileExist(path + fileName) && !cover){ return FILEEXIST; } try { inputStream = getInputStreamFromUrl(urlStr); File resultFile = FileUtils.writData2SDFromInputStream(path, fileName, inputStream); if(resultFile == null){ return DOWNLOADFAIL; } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); return DOWNLOADFAIL; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); //网络文件未找到 return DOWNLOADFAIL; } try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } return DOWNLOADSUCCESS; } /** * 根据url地址得到输入流 * @param urlStr * @throws MalformedURLException * @throws IOException */ public InputStream getInputStreamFromUrl(String urlStr)throws MalformedURLException,IOException{ HttpURLConnection urlConn = null; InputStream resInput = null; url = new URL(urlStr); urlConn = (HttpURLConnection)url.openConnection(); resInput = urlConn.getInputStream(); return resInput; } }
文件工具类FileUtils.java:
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 static String SDPATH; static{ SDPATH = Environment.getExternalStorageDirectory() + File.separator; } /** * 在SD卡上创建文件 * @param fileName * @return * @throws IOException */ public static File creatFileOnSD(String fileName) throws IOException{ File file = new File(SDPATH + fileName); file.createNewFile(); return file; } /** * 在SD卡上创建目录 * @param dirName * @return */ public static File creatDirOnSD(String dirName){ File dir = new File(SDPATH + dirName); dir.mkdir(); return dir; } /** * 判断文件在SD卡上是否存在 * @param fileName * @return */ public static boolean isFileExist(String fileName){ File file = new File(SDPATH + fileName); return file.exists(); } /** * 将输入流里的数据写入SD卡中 * @param path 写入文件存放路径 * @param fileName 生成的文件名 * @param input 输入流 * @return */ public static File writData2SDFromInputStream(String path, String fileName,InputStream inputStream){ File file = null; OutputStream output = null; try { creatDirOnSD(path); file = creatFileOnSD(path + fileName); output = new FileOutputStream(file); //每4K输出一次 byte buffer[] = new byte[4 * 1024]; while(inputStream.read(buffer) != -1){ output.write(buffer); } //清除缓存 output.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; }finally{ try { output.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return file; } }
Activity的代码:
btnDownloadTxt.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // 得到text内容 HttpDownloader httpDownloader = new HttpDownloader(); String res = httpDownloader.download("http://192.168.2.15:6060/tianfangUploadImg/text/news/ttt"); System.out.println(res); } }); btnDownloadMp3.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub HttpDownloader httpDownloader = new HttpDownloader(); int res = httpDownloader.download("http://127.0.0.1:6060/test/sounds/test.mp3", "mp3/", "newMap3.mp3", true); if(HttpDownloader.DOWNLOADSUCCESS == res){ System.out.println("下载成功"); } if(HttpDownloader.DOWNLOADFAIL == res){ System.out.println("下载失败"); } if(HttpDownloader.FILEEXIST == res){ System.out.println("文件已存在"); } } });
在网上查看有些高手说用android访问本机电脑服务器可用ip:10.0.2.2
如果你想在模拟器simulator上面访问你的电脑,那么就使用android内置的IP10.0.2.2吧, 10.0.2.2 是模拟器设置的特定ip,是你的电脑的别名alias
记住,在模拟器上用10.0.2.2访问你的电脑本机