标签:android 文件下载 private public return
工具类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文件时会存在问题,暂未解决。
本文出自 “阿凡达” 博客,请务必保留此出处http://shamrock.blog.51cto.com/2079212/1580269
标签:android 文件下载 private public return
原文地址:http://shamrock.blog.51cto.com/2079212/1580269