工具類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);
}
}免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。