工具类FileUtils.java
package com.example.filedownload_01; 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; public String getSDPATH() { return SDPATH; } public FileUtils() { //得到当前外部存储设备的目录 一般是/sdcard SDPATH = Environment.getExternalStorageDirectory() + "/"; } /** * 在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 dirName 目录名 * @return */ public File createSDDir(String dirName) { File dir = new File(SDPATH + dirName); dir.mkdir(); return dir; } /** * 判断SD卡上是否存在文件 * @param fileName * @return */ public boolean isFileExist(String fileName) { File file = new File(SDPATH + fileName); return file.exists(); } /** * 将一个InputStream里面的数据写入到SD卡中 * @param path 路径 * @param fileName 文件名 * @param input 输入流 * @return 写入SD卡的文件 */ public File write2SDFromInput(String path, String fileName, InputStream input) { File file = null; OutputStream output = null; try { createSDDir(path); file = createSDFile(path + fileName); output = new FileOutputStream(file); byte buffer[] = new byte[4 * 1024]; while ((input.read(buffer)) != -1) { output.write(buffer); } output.flush(); } catch (Exception e) { e.printStackTrace(); }finally{ try { output.close(); } catch (Exception e2) { e2.printStackTrace(); } } return file; } }
HttpDownloader.java
package com.example.filedownload_01; 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 org.apache.http.message.BufferedHeader; public class HttpDownloader { private URL url = null; public String download(String urlStr) { StringBuffer sb = new StringBuffer(); String line = null; BufferedReader buffer = null; try { url = new URL(urlStr); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); buffer = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); while ((line = buffer.readLine()) != null) { sb.append(line); } } catch (Exception e) { e.printStackTrace(); } finally { try { buffer.close(); } catch (Exception e2) { e2.printStackTrace(); } } return sb.toString(); } /** * @param urlStr * url * @param path * 保存路径 * @param fileName * 文件名 * @return 返回值-1:表示下载文件出错,0表示下载文件成功,1表示文件已经存在 */ public int downloadFile(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 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; } public InputStream getInputStreamFromUrl(String urlStr) throws IOException { url = new URL(urlStr); HttpURLConnection urlConnection = (HttpURLConnection) url .openConnection(); InputStream inputStream = urlConnection.getInputStream(); return inputStream; } }
MainActivity.java
package com.example.filedownload_01; import android.support.v7.app.ActionBarActivity; import android.R.integer; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends ActionBarActivity { private Button downloadTxtButton = null; private Button downloadMp3Button = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); downloadMp3Button = (Button) findViewById(R.id.downloadMp3Button); downloadTxtButton = (Button) findViewById(R.id.downloadTxtButton); downloadTxtButton.setOnClickListener(new DownloadTextListener()); downloadMp3Button.setOnClickListener(new DownloadMp3Listener()); } class DownloadTextListener implements OnClickListener { @Override public void onClick(View v) { System.out.println("下载TXT文件"); Toast.makeText(MainActivity.this, "开始下载TXT", Toast.LENGTH_SHORT).show(); String urlStr = "http://www.51voa.com/lrc/201411/se-health-surgical-safari-cosmetic-18nov14.lrc"; String path = "umgsai_download/"; String fileName = "test.lrc"; //生成一个HandlerThread对象,实现了使用Looper来处理消息队列的功能 HandlerThread handlerThread = new HandlerThread("handler_Thread"); handlerThread.start(); MyHandler myHandler = new MyHandler(handlerThread.getLooper()); Message msg = myHandler.obtainMessage(); //msg.obj = "abc"; //简单数据 Bundle bundle = new Bundle(); bundle.putString("urlStr", urlStr); bundle.putString("fileName", fileName); bundle.putString("path", path); msg.setData(bundle); //将msg发送到目标对象,即生成msg对象的Handler对象 msg.sendToTarget(); //HttpDownloader httpDownloader = new HttpDownloader(); //String lrc = httpDownloader.download("http://localhost/menu/log.txt"); //System.out.println(lrc); } } class DownloadMp3Listener implements OnClickListener{ @Override public void onClick(View v) { // HttpDownloader httpDownloader = new HttpDownloader(); // int result = httpDownloader.downloadFile("", "voa/", "test.mp3"); // System.out.println(result); Toast.makeText(MainActivity.this, "开始下载MP3", Toast.LENGTH_SHORT).show(); String urlStr = "http://127.0.0.1/menu/test.apk"; String path = "umgsai_download/"; String fileName = "test.apk"; //生成一个HandlerThread对象,实现了使用Looper来处理消息队列的功能 HandlerThread handlerThread = new HandlerThread("handler_Thread"); handlerThread.start(); MyHandler myHandler = new MyHandler(handlerThread.getLooper()); Message msg = myHandler.obtainMessage(); //msg.obj = "abc"; //简单数据 Bundle bundle = new Bundle(); bundle.putString("urlStr", urlStr); bundle.putString("fileName", fileName); bundle.putString("path", path); msg.setData(bundle); //将msg发送到目标对象,即生成msg对象的Handler对象 msg.sendToTarget(); } } class MyHandler extends Handler{ public MyHandler() { } public MyHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { super.handleMessage(msg); Bundle bundle = msg.getData(); String urlStr = bundle.getString("urlStr"); String fileName = bundle.getString("fileName"); String path = bundle.getString("path"); HttpDownloader httpDownloader = new HttpDownloader(); int result = httpDownloader.downloadFile(urlStr, path, fileName); System.out.println(result); Toast.makeText(MainActivity.this, "~~", Toast.LENGTH_SHORT).show(); // String lrc = httpDownloader.download(fileName); // System.out.println(lrc); } } }
下载文件的任务不能放在主线程里面,否则会抛异常。
下载MP3文件时会存在问题,暂未解决。
把上面的代码重新整理了一份
FileUtils.java
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; public String getSDPATH() { return SDPATH; } public FileUtils() { //得到当前外部存储设备的目录 // /SDCARD SDPATH = Environment.getExternalStorageDirectory() + "/"; } /** * 在SD卡上创建文件 * * @throws IOException */ public File creatSDFile(String fileName) throws IOException { File file = new File(SDPATH + fileName); file.createNewFile(); return file; } /** * 在SD卡上创建目录 * * @param dirName */ public File creatSDDir(String dirName) { File dir = new File(SDPATH + dirName); dir.mkdir(); return dir; } /** * 判断SD卡上的文件夹是否存在 */ public boolean isFileExist(String fileName){ File file = new File(SDPATH + 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 = creatSDFile(path + fileName); output = new FileOutputStream(file); byte buffer [] = new byte[4 * 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; } }
HttpDownloader.java
package com.example.utils; 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 = 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(path + fileName)) { 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; } }
下载不能在主线程里进行
class Mp3ButtonListener implements OnClickListener { @Override public void onClick(View v) { // TODO Auto-generated method stub String urlStr = "http://192.168.77.215/jstree/snowdreams.mp3"; String path = "umgsai_download/"; String fileName = "snowdreams.mp3"; // 生成一个HandlerThread对象,实现了使用Looper来处理消息队列的功能 HandlerThread handlerThread = new HandlerThread("handler_Thread"); handlerThread.start(); Mp3Handler mp3Handler = new Mp3Handler(handlerThread.getLooper()); Message msg = mp3Handler.obtainMessage(); Bundle bundle = new Bundle(); bundle.putString("urlStr", urlStr); bundle.putString("fileName", fileName); bundle.putString("path", path); msg.setData(bundle); // 将msg发送到目标对象,即生成msg对象的Handler对象 msg.sendToTarget(); } } class Mp3Handler extends Handler { public Mp3Handler() { } public Mp3Handler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); Bundle bundle = msg.getData(); String urlStr = bundle.getString("urlStr"); String fileName = bundle.getString("fileName"); String path = bundle.getString("path"); HttpDownloader httpDownloader = new HttpDownloader(); int result = httpDownloader.downFile(urlStr, path, fileName); System.err.println(result); Toast.makeText(MainActivity.this, result + "~~", Toast.LENGTH_SHORT) .show(); } }
需要连接网络和向外部存储设备写数据的权限
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
在模拟器上测试正常,但是在真机上测试出问题。暂未解决。开发中建议使用这里的代码。第一次整理的代码可能存在问题,未测试。
读取网络文件内容如下
class ParseButtonListener implements OnClickListener { @Override public void onClick(View v) { String urlStr = "http://192.168.77.215/jstree/test.xml"; String path = "umgsai_download/"; String fileName = "test.lrc"; // 生成一个HandlerThread对象,实现了使用Looper来处理消息队列的功能 HandlerThread handlerThread = new HandlerThread("handler_Thread"); handlerThread.start(); MyHandler myHandler = new MyHandler(handlerThread.getLooper()); Message msg = myHandler.obtainMessage(); // msg.obj = "abc"; //简单数据 Bundle bundle = new Bundle(); bundle.putString("urlStr", urlStr); bundle.putString("fileName", fileName); bundle.putString("path", path); msg.setData(bundle); // 将msg发送到目标对象,即生成msg对象的Handler对象 msg.sendToTarget(); }
class MyHandler extends Handler { public MyHandler() { } public MyHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { super.handleMessage(msg); Bundle bundle = msg.getData(); String urlStr = bundle.getString("urlStr"); String fileName = bundle.getString("fileName"); String path = bundle.getString("path"); HttpDownloader httpDownloader = new HttpDownloader(); String result = httpDownloader.download(urlStr); System.err.println(result); Toast.makeText(MainActivity.this, "~~", Toast.LENGTH_SHORT).show(); // String lrc = httpDownloader.download(fileName); // System.out.println(lrc); } }