android下载文件到本地sdcard

hellosmile 2014-02-11 11:04:51
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();
}

/**
* 将一个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;
}
}


程序运行后提示:

请各位帮忙看下,谢谢!
...全文
1027 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
xushan11375 2016-07-11
  • 打赏
  • 举报
回复
按钮的点击事件为什么你要写在子线程里面
酷酷熊猫 2015-07-27
  • 打赏
  • 举报
回复
这个是单线程下载还是多线程下载
莺时桃桃 2014-02-14
  • 打赏
  • 举报
回复
引用 10 楼 wangdoudou1990 的回复:
现在问题是真机测试也下载不下来,会很慢,然后就提示“android应用无响应”。求解
真机应该是可以对SD卡操作的 我用过的 很慢 无响应的话 貌似是不是哪里死循环了呢? 比如这里 你打印一下调试信息看看啊
while (true) {
                int temp = input.read(buffer, 0, buffer.length);
                if (temp == -1) {
                    break;
                }
                output.write(buffer, 0, temp);
            }
517967268 2014-02-14
  • 打赏
  • 举报
回复
你试试在异步里面下载文件吧 http://jackyrong.iteye.com/blog/1336299
hellosmile 2014-02-13
  • 打赏
  • 举报
回复
现在问题是真机测试也下载不下来,会很慢,然后就提示“android应用无响应”。求解
s478853630 2014-02-12
  • 打赏
  • 举报
回复
进度条呀,上传下载必须要有进度条,否则很不友好的
private int fileSize = 0;
	private ProgressDialog progress = null;

gressDialog = new ProgressDialog(this);
				gressDialog.setCanceledOnTouchOutside(true);
				gressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				gressDialog.setMessage("正在下载文件...");
				gressDialog.show();
hellosmile 2014-02-12
  • 打赏
  • 举报
回复
引用 2 楼 s478853630 的回复:
/**
	 * 把网络上的文件保存到sd卡
	 * @param url 完整的可访问的url
	 * @param file 文件
	 * @return boolean
	 */
	public boolean saveUrlFile(String url, File file) throws Exception {
		HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
		fileSize = conn.getContentLength();
		InputStream input = conn.getInputStream();
		if (null != input) {
			copyFile(input, file);
			conn.disconnect();
			return true;
		}
		return false;
	}
/**
	 * 复制文件
	 * @param input 输入流
	 * @param newFile 新文件
	 * @throws Exception
	 */
	public void copyFile(InputStream input, File newFile) throws Exception {
		if (null != progress) {progress.setMax(fileSize);}
		OutputStream output = new FileOutputStream(newFile);
		byte[] buffer = new byte[1024];
		int i = 0, total = 0;
		while ((i = input.read(buffer)) != -1) {
			output.write(buffer, 0, i);
			total += i;
			if (null != progress) {progress.setProgress(total);}
		}
		output.flush();output.close();input.close();
	}
带进度条的文件下载
progress 是什么?
莺时桃桃 2014-02-12
  • 打赏
  • 举报
回复
引用 8 楼 wangdoudou1990 的回复:
[quote=引用 7 楼 u013645219 的回复:] 亲 增加权限 在你的AndroidMainifest.xml 里在"<application "前面增加这几句话
	
        <!-- 在SDCard中创建与删除文件权限 -->
	<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
	<!-- 往SDCard写入数据权限 -->
	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
这些权限我已经加过了,真机运行不会提示权限被禁止,用模拟器运行时会提示。[/quote] 哦 懂了 这个我也试过,但貌似模拟器上不能调试SD卡吧。。。。没弄出来。。
s478853630 2014-02-12
  • 打赏
  • 举报
回复
/**
	 * 把网络上的文件保存到sd卡
	 * @param url 完整的可访问的url
	 * @param file 文件
	 * @return boolean
	 */
	public boolean saveUrlFile(String url, File file) throws Exception {
		HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
		fileSize = conn.getContentLength();
		InputStream input = conn.getInputStream();
		if (null != input) {
			copyFile(input, file);
			conn.disconnect();
			return true;
		}
		return false;
	}
/**
	 * 复制文件
	 * @param input 输入流
	 * @param newFile 新文件
	 * @throws Exception
	 */
	public void copyFile(InputStream input, File newFile) throws Exception {
		if (null != progress) {progress.setMax(fileSize);}
		OutputStream output = new FileOutputStream(newFile);
		byte[] buffer = new byte[1024];
		int i = 0, total = 0;
		while ((i = input.read(buffer)) != -1) {
			output.write(buffer, 0, i);
			total += i;
			if (null != progress) {progress.setProgress(total);}
		}
		output.flush();output.close();input.close();
	}
带进度条的文件下载
hellosmile 2014-02-12
  • 打赏
  • 举报
回复
引用 7 楼 u013645219 的回复:
亲 增加权限 在你的AndroidMainifest.xml 里在"<application "前面增加这几句话
	
        <!-- 在SDCard中创建与删除文件权限 -->
	<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
	<!-- 往SDCard写入数据权限 -->
	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
这些权限我已经加过了,真机运行不会提示权限被禁止,用模拟器运行时会提示。
莺时桃桃 2014-02-12
  • 打赏
  • 举报
回复
亲 增加权限 在你的AndroidMainifest.xml 里在"<application "前面增加这几句话
	
        <!-- 在SDCard中创建与删除文件权限 -->
	<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
	<!-- 往SDCard写入数据权限 -->
	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
juen32 2014-02-12
  • 打赏
  • 举报
回复
我发现你 HttpURLConnection  用完不关闭 ,还有流用完随手关闭 好习惯
hellosmile 2014-02-12
  • 打赏
  • 举报
回复
为什么我以点击下载按钮就是无响应呢,求解,是用的真机测试。在模拟器上运行就会提示权限被禁止。
hellosmile 2014-02-11
  • 打赏
  • 举报
回复
为什么没人回复哇。。。

80,360

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧