重慶分公司,新征程啟航
為企業(yè)提供網(wǎng)站建設(shè)、域名注冊(cè)、服務(wù)器等服務(wù)
為企業(yè)提供網(wǎng)站建設(shè)、域名注冊(cè)、服務(wù)器等服務(wù)
工具類(lèi)FileUtils.java
我們提供的服務(wù)有:網(wǎng)站制作、成都做網(wǎng)站、微信公眾號(hào)開(kāi)發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、中山ssl等。為上1000家企事業(yè)單位解決了網(wǎng)站和推廣的問(wèn)題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的中山網(wǎng)站制作公司
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() { //得到當(dāng)前外部存儲(chǔ)設(shè)備的目錄 一般是/sdcard SDPATH = Environment.getExternalStorageDirectory() + "/"; } /** * 在SD卡上創(chuàng)建文件 * @param fileName 文件名 * @return 新創(chuàng)建的文件 * @throws IOException */ public File createSDFile(String fileName) throws IOException { File file = new File(SDPATH + fileName); file.createNewFile(); return file; } /** * 在SD卡上創(chuàng)建目錄 * @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(); } /** * 將一個(gè)InputStream里面的數(shù)據(jù)寫(xiě)入到SD卡中 * @param path 路徑 * @param fileName 文件名 * @param input 輸入流 * @return 寫(xiě)入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:表示下載文件出錯(cuò),0表示下載文件成功,1表示文件已經(jīng)存在 */ public int downloadFile(String urlStr, String path, String fileName) { InputStream inputStream = null; try { FileUtils fileUtils = new FileUtils(); if (fileUtils.isFileExist(path + fileName)) { return 1;// 文件已經(jīng)存在 } 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, "開(kāi)始下載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"; //生成一個(gè)HandlerThread對(duì)象,實(shí)現(xiàn)了使用Looper來(lái)處理消息隊(duì)列的功能 HandlerThread handlerThread = new HandlerThread("handler_Thread"); handlerThread.start(); MyHandler myHandler = new MyHandler(handlerThread.getLooper()); Message msg = myHandler.obtainMessage(); //msg.obj = "abc"; //簡(jiǎn)單數(shù)據(jù) Bundle bundle = new Bundle(); bundle.putString("urlStr", urlStr); bundle.putString("fileName", fileName); bundle.putString("path", path); msg.setData(bundle); //將msg發(fā)送到目標(biāo)對(duì)象,即生成msg對(duì)象的Handler對(duì)象 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, "開(kāi)始下載MP3", Toast.LENGTH_SHORT).show(); String urlStr = "http://127.0.0.1/menu/test.apk"; String path = "umgsai_download/"; String fileName = "test.apk"; //生成一個(gè)HandlerThread對(duì)象,實(shí)現(xiàn)了使用Looper來(lái)處理消息隊(duì)列的功能 HandlerThread handlerThread = new HandlerThread("handler_Thread"); handlerThread.start(); MyHandler myHandler = new MyHandler(handlerThread.getLooper()); Message msg = myHandler.obtainMessage(); //msg.obj = "abc"; //簡(jiǎn)單數(shù)據(jù) Bundle bundle = new Bundle(); bundle.putString("urlStr", urlStr); bundle.putString("fileName", fileName); bundle.putString("path", path); msg.setData(bundle); //將msg發(fā)送到目標(biāo)對(duì)象,即生成msg對(duì)象的Handler對(duì)象 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); } } }
下載文件的任務(wù)不能放在主線程里面,否則會(huì)拋異常。
下載MP3文件時(shí)會(huì)存在問(wèn)題,暫未解決。
把上面的代碼重新整理了一份
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() { //得到當(dāng)前外部存儲(chǔ)設(shè)備的目錄 // /SDCARD SDPATH = Environment.getExternalStorageDirectory() + "/"; } /** * 在SD卡上創(chuàng)建文件 * * @throws IOException */ public File creatSDFile(String fileName) throws IOException { File file = new File(SDPATH + fileName); file.createNewFile(); return file; } /** * 在SD卡上創(chuàng)建目錄 * * @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(); } /** * 將一個(gè)InputStream里面的數(shù)據(jù)寫(xiě)入到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; /** * 根據(jù)URL下載文件,前提是這個(gè)文件當(dāng)中的內(nèi)容是文本,函數(shù)的返回值就是文件當(dāng)中的內(nèi)容 * 1.創(chuàng)建一個(gè)URL對(duì)象 * 2.通過(guò)URL對(duì)象,創(chuàng)建一個(gè)HttpURLConnection對(duì)象 * 3.得到InputStram * 4.從InputStream當(dāng)中讀取數(shù)據(jù) * @param urlStr * @return */ public String download(String urlStr) { StringBuffer sb = new StringBuffer(); String line = null; BufferedReader buffer = null; try { // 創(chuàng)建一個(gè)URL對(duì)象 url = new URL(urlStr); // 創(chuàng)建一個(gè)Http連接 HttpURLConnection urlConn = (HttpURLConnection) url .openConnection(); // 使用IO流讀取數(shù)據(jù) 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(); } /** * 該函數(shù)返回××× -1:代表下載文件出錯(cuò) 0:代表下載文件成功 1:代表文件已經(jīng)存在 */ 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; } /** * 根據(jù)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; } }
下載不能在主線程里進(jìn)行
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"; // 生成一個(gè)HandlerThread對(duì)象,實(shí)現(xiàn)了使用Looper來(lái)處理消息隊(duì)列的功能 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發(fā)送到目標(biāo)對(duì)象,即生成msg對(duì)象的Handler對(duì)象 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(); } }
需要連接網(wǎng)絡(luò)和向外部存儲(chǔ)設(shè)備寫(xiě)數(shù)據(jù)的權(quán)限
在模擬器上測(cè)試正常,但是在真機(jī)上測(cè)試出問(wèn)題。暫未解決。開(kāi)發(fā)中建議使用這里的代碼。第一次整理的代碼可能存在問(wèn)題,未測(cè)試。
讀取網(wǎng)絡(luò)文件內(nèi)容如下
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"; // 生成一個(gè)HandlerThread對(duì)象,實(shí)現(xiàn)了使用Looper來(lái)處理消息隊(duì)列的功能 HandlerThread handlerThread = new HandlerThread("handler_Thread"); handlerThread.start(); MyHandler myHandler = new MyHandler(handlerThread.getLooper()); Message msg = myHandler.obtainMessage(); // msg.obj = "abc"; //簡(jiǎn)單數(shù)據(jù) Bundle bundle = new Bundle(); bundle.putString("urlStr", urlStr); bundle.putString("fileName", fileName); bundle.putString("path", path); msg.setData(bundle); // 將msg發(fā)送到目標(biāo)對(duì)象,即生成msg對(duì)象的Handler對(duì)象 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); } }