import com.example.android.R;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity3 extends Activity {
private Button downfile = null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
downfile = (Button) findViewById(R.id.downfile);

new Thread() {
@Override
public void run() {
// 你要执行的方法
downfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
HttpDownloader httpDownLoader = new HttpDownloader();
int result = httpDownLoader
.downfile(
"http://192.168.5.60:8080/statics/images//bdxz_btn.jpg",
"test/", "test.jpg");
// if (result == 0) {
// Toast.makeText(MainActivity3.this, "下载成功!",
// Toast.LENGTH_SHORT).show();
// } else if (result == 1) {
// Toast.makeText(MainActivity3.this, "已有文件!",
// Toast.LENGTH_SHORT).show();
// } else if (result == -1) {
// Toast.makeText(MainActivity3.this, "下载失败!",
// Toast.LENGTH_SHORT).show();
// }
}
});
// 执行完毕后给handler发送一个空消息
handler.sendEmptyMessage(0);
}
}.start();
}

// 定义Handler对象
private Handler handler = new Handler() {
@Override
// 当有消息发送出来的时候就执行Handler的这个方法
public void handleMessage(Message msg) {
super.handleMessage(msg);
// 处理UI
Log.e("MAINACTIVITY3", "" + msg);
}

};
}
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 createSDFile(String fileName) throws IOException {
File file = new File(SDPATH + fileName);
file.createNewFile();
return file;
}

/**
* 在SD卡上创建目录
*
* @param dirName
*/
public File createSDDir(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();
}

/**


* 该函数返回整形-1:代表下载文件出错。
* 0:代表下载文件成功
* 1:代表下载文件经存在

* 将一个InputStream里面的数据写入到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);
// }

while (true) {
int temp = input.read(buffer, 0, buffer.length);
if (temp == -1) {
break;
}
output.write(buffer, 0, temp);
}

output.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return file;
}
}
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpDownloader {
private URL url = null;
FileUtils fileUtils = new FileUtils();

public int downfile(String urlStr, String path, String fileName) {
if (fileUtils.isFileExist(path + fileName)) {
return 1;
} else {

try {
InputStream input = null;
input = getInputStream(urlStr);
File resultFile = fileUtils.write2SDFromInput(path, fileName,
input);
if (resultFile == null) {
return -1;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
return 0;
}

// 由于得到一个InputStream对象是所有文件处理前必须的操作,所以将这个操作封装成了一个方法
public InputStream getInputStream(String urlStr) throws IOException {
InputStream is = null;
try {
url = new URL(urlStr);
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
urlConn.setRequestProperty("Connection", "close");
urlConn.connect();
is = urlConn.getInputStream();

} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return is;
}
}

android 下载文件的更多相关文章

  1. Android 下载文件及写入SD卡

    Android 下载文件及写入SD卡,实例代码 <?xml version="1.0" encoding="utf-8"?> <LinearL ...

  2. 基于Android 下载文件时,更新UI简单帮助类

    因为在项目开发时.有这种简单需求,问谷歌,网络上也有好多Utils工具类,可是比較冗余.自己就简单的写了一个简单帮助类. /** * 下载文件,更新UI简单帮助类 * * @author jarlen ...

  3. android 下载文件,file的读写应用

    先看代码: public class MainActivity extends AppCompatActivity { String TAG = MainActivity.class.getCanon ...

  4. Android 下载文件 显示进度条

    加入两个权限 一个是联网,另一个是读写SD卡 <uses-permission android:name="android.permission.INTERNET">& ...

  5. Android下载文件提示文件不存在。。。 java.io.FileNotFoundException

    遇到这个错误java.io.FileNotFoundException,事实上文件是存在的,把地址复制到手机浏览器都能够直接下载的,但为嘛不能下载呢. Error in downloadBitmap ...

  6. Android下载文件到SD卡

    HttpURLConnection 上传方式: 尝试理解这两种流的区别: InputStreamReader 的读取方式: //创建一个URL对象 URL url = new URL(urlStrin ...

  7. 主线程中一定不能放耗时操作,必须要开子线程,比如下载文件,不然会不让你拿到输入流--报错显示android.os.NetworkOnMainThreadException

    1.必须要开子线程来操作耗时操作,android.os.NetworkOnMainThreadException new Thread(new Runnable() { @Override publi ...

  8. Android之访问下载文件

    1.SD卡操作类 FileUtils.java package com.example.mars_1500_download; import java.io.File; import java.io. ...

  9. Android利用Http下载文件

    Android利用Http下载文件 一.场景 下载存文本文件和下载如mp3等大容量的文件 界面 二.代码编写 1.AndroidMainfest.xml中配置 主要是解决网络权限和写SDCard的权限 ...

随机推荐

  1. JavaScript学习07 内置对象

    JavaScript内置对象 图像对象 导航对象 窗口对象 屏幕对象 事件对象 历史对象 文件对象(重要) 锚点对象 链接对象 框架对象 表单对象(重要) 位置对象 JS Window 窗口对象:ht ...

  2. SwipeBackActivity 的使用

    1.SwipeBackLayout 项目地址:https://github.com/ikew0ng/SwipeBackLayout 2.用法 android studio  compile 'me.i ...

  3. Android 采用post方式提交数据到服务器

    接着上篇<Android 采用get方式提交数据到服务器>,本文来实现采用post方式提交数据到服务器 首先对比一下get方式和post方式: 修改布局: <LinearLayout ...

  4. OC NSNumber NSValue

    OC NSNumber NSValue iOS的集合对象不可以存储C语言基本类型,所有可以进行装箱和拆箱,来进行OC对象操作. NSNumber包装类 普通初始化 NSNumber * num1 = ...

  5. IOS设计模式-观察者模式

    前言:23种软件设计模式中的观察者模式,也是在软件开发中,挺常用的一种设计模式.而在苹果开发中,苹果Cocoa框架已经给我们实现了这个设 计模式,那就是通知和KVO(Key-Value Observi ...

  6. NTP服务器引起的上行带宽超大

    2014年2月11日,centos服务器突然上行带宽8M,耗光所有带宽,不能远程SSH登录维护. 到机房直接使用界面登录,安装iptraf,运行后选择 Statistical breakdowns - ...

  7. python 打印对象的所有属性值

    def prn_obj(obj): print '\n'.join(['%s:%s' % item for item in obj.__dict__.items()])

  8. 天书笔记:如何创建一个现代的footer(页脚)

    此笔记纯属本人脑残笔记,阅读困难不理解属正常现象,初学者尽量不要阅读,否则轻则口吐白沫重则走火入魔,切记切记 老规矩,效果图 这个布局也是从b站看到的,回来自己实现了一遍 HTML: <div ...

  9. ORACLE TO_CHAR函数格式化数字的出现空格的原因

    在这篇博客SQL挑战--如何高效生成编码里面我由于需要将数字格式化为字符,像12需要格式化0012这样的字符,所以使用了TO_CHAR(数字,'0000')这样的写法,后面0000表示缺省补零,测试过 ...

  10. maven 安装alipay-sdk包到本地及远程仓库

    安装到本地:mvn install:install-file -DgroupId=com.alipay -DartifactId=sdk-Java -Dversion=*** -Dpackaging= ...