笔记摘要:
本例主要使用了IO流的相关技术,装饰类,转换流,文件的读取和写入以及流对象的关闭
File对象的相关操作:
获取File对象,根据路径创建文件夹,判断文件是否存在,创建文件,将各个方法封装到工具类中,提高复用性
Url技术:字符串到Url的转换:url = new URL(urlStr);
获取Http连接服务:HttpURLConnection con = (HttpURLConnection)url.openConnection();
Tomcat服务器:
资源文件:C:\apache-tomcat-6.0.35\webapps\test\haha.txt
C:\apache-tomcat-6.0.35\webapps\test\1.mp3
使用dos命令查询结果:adb shell、cd sdcard、cd test、ls
查询结果:1.mp3.
注意:
在AndroidMainfest.xml 文件中记得对SD卡访问权限的声明:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
发现的错误:
快捷键使用错误:
HttpURLConnection con = (HttpURLConnection)url.openConnection();//快捷键使用错误应为:HttpsURLConnection
SDPATH = Environment.getExternalStorageDirectory()+"/";//快捷键使用出错,应为:getExternalStorageState()
示例代码
布局文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/downloadTxt"
android:text="下载文本文件"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/downloadMp3"
android:text="下载MP3文件"
android:layout_below="@id/downloadTxt"
/>
</RelativeLayout>
下载类中使用到的工具类代码:
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;
import android.util.Log;
public class FileUtils {
private String SDPATH;
private static final String TAG = "FileUtils";
public FileUtils(){
SDPATH = Environment.getExternalStorageDirectory()+"/";//快捷键使用出错:getExternalStorageState()
}
//得到当前外部存储设备的目录
public String getSDPATH(){
return SDPATH;
}
//在SD卡上创建文件:
public File createSDFile(String dirAndFilename) throws IOException{
File file = new File(SDPATH+dirAndFilename);
file.createNewFile();
return file;
}
//在SD卡上创建目录
public File createSDDir(String dirName){
File dir = new File(SDPATH+dirName);
dir.mkdirs();
return dir;
}
//判断SD卡上的文件夹是否存在
public boolean isFileExist(String fileName){
File file = new File(SDPATH + fileName);
return file.exists();
}
//将一个InputStream里面的数据写到SD卡中
public File write2SDFromInputStream(String path,String fileName,InputStream in){
File file = null;
OutputStream out = null;
try {
createSDDir(path);
try{file = createSDFile(path+fileName);}
catch(Exception e){
System.out.println("createSDFile 失败");
}
out = new FileOutputStream(file);
byte buf[] = new byte[1024*5];
int ch = 0;
while((ch = in.read(buf))!=-1){
out.write(buf);
out.flush();
}
} catch (IOException e) {
System.out.println("SD写入失败!");
e.printStackTrace();
}finally{
if(out!=null)
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("SD写入流关闭失败!");
}
}
return file;
}
}
下载方法类:
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.URL;
import android.util.Log;
/*思路:首先判断所下载的文件是否为纯文本文件
* 1.创建一个Url对象
* 2.通过Url对象获取HttpOpenConnection对象
* 3.获取InputStream对象
* 4.读取数据
* 5.将读取的数据写入SD卡
*
* */
public class HttpDownload {
private URL url = null;
private static final String TAG = "HttpDownload";
//下载普通纯文本文件
public String download(String urlStr){
String line = null;
StringBuffer sb = new StringBuffer();
BufferedReader bufr = null;
try { // 创建一个URL对象
url = new URL(urlStr);
//创建一个Http连接 HttpURLConnection con = (HttpURLConnection)url.openConnection();//快捷键使用错误:HttpsURLConnection
//使用IO流读取数据,这里使用到了转换流,提高读取效率 bufr = new BufferedReader(new InputStreamReader(con.getInputStream()));
while((line = bufr.readLine())!=null){
sb.append(line);
}
} catch (Exception e) {
System.out.println("文本文件下载失败!");
}finally{
if(bufr!=null)
try {
bufr.close();
} catch (IOException e) {
System.out.println("文本文件读取流关闭失败!");
}
}
return sb.toString();
}
//可下载各种文件
//返回 -1:代表下载文件出错, 返回0:代表下载文件成功,返回 1:代表文件已经存在
//fileName代表你将要存入SD卡中的文件名,可以定义自己的文件名
public int downloadFile(String url,String path,String fileName){
InputStream in = null;
try {
FileUtils utils = new FileUtils() ;
if(utils.isFileExist(path+fileName)){
return 1;
}else{
in = getInputStreamFromUrl(url);
File resultFile = utils.write2SDFromInputStream(path, fileName, in);
if(resultFile == null){
return -1;
}
}
} catch (IOException e) {
e.printStackTrace();
return -1;
}finally{
if(in!=null){
try {
in.close();
} catch (IOException e) {
System.out.println("字节读取流关闭失败!");
}
}
}
return 0;
}
//将根据Url获取InputStream的功能封装起来,以便复用
public InputStream getInputStreamFromUrl(String urlStr) throws IOException{
url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
InputStream in = con.getInputStream();
return in;
}
}
Activity代码:
package com.example.downloadfile;
import com.example.Utils.HttpDownload;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Download extends Activity {
private Button downloadTxtBtn ;
private Button downloadMp3Btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
downloadTxtBtn = (Button) findViewById(R.id.downloadTxt);
downloadMp3Btn = (Button) findViewById(R.id.downloadMp3);
downloadTxtBtn.setOnClickListener(new DownloadTxtListener());
downloadMp3Btn.setOnClickListener(new DownloadMp3Listener());
}
private final class DownloadTxtListener implements OnClickListener{
public void onClick(View v) {
HttpDownload hdl = new HttpDownload();
String file = hdl.download("http://169.254.57.236:8080/test/haha.txt");
System.out.println(file);
}
}
private final class DownloadMp3Listener implements OnClickListener{
public void onClick(View v) {
// TODO Auto-generated method stub
HttpDownload hdl = new HttpDownload();
hdl.downloadFile("http://169.254.57.236/test/1.mp3","test/","1.mp3");
System.out.println("DownMp3 Done!!!!");
}
}
}
个人心得:
本例子是前两天写的,当时没有能够调试成功,就放弃了,后来进行新的学习时,总觉得不对劲,又把前两天学习的东西进行调试总结,
虽然感觉有些乏味,但大多时候还是自己的懒惰与浮躁,总想一口吃块肉。在这个过程中也是不断学习和提升的过程,而且十分有必要,
只是一味地追求进度,并没有理解,掌握,还不如不学,要学就扎扎实实的,把不会的,没解决的问题弄清楚,再进行新的学习,并且定
期地复习,这样效率才能提高。
自我勉励:静下心,学扎实,勤动手,多复习
Mars视频与学习论坛:http://www.mars-droid.com/bbs/forum.php