Android之访问下载文件
1.SD卡操作类 FileUtils.java
package com.example.mars_1500_download; 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.mkdirs();
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;
} }
2.下载类HttpDownloader
package com.example.mars_1500_download; 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) {
System.out.println("download:" + e.getMessage());
e.printStackTrace();
} finally {
try {
buffer.close();
} catch (Exception e) {
System.out.println("download buffer.close():" + e.getMessage());
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) {
System.out.println("downFile:" + e.getMessage());
e.printStackTrace();
return -1;
} finally {
try {
inputStream.close();
} catch (Exception e) {
System.out.println("downFile close:" + e.getMessage());
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;
}
}
3.下载文件Activity
package com.example.mars_1500_download; import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.os.Build; public class MainActivity extends Activity {
private Button downloadTxtButton;
private Button downloadMp3Button; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); downloadTxtButton=(Button)findViewById(R.id.downloadTxtButton);
downloadMp3Button=(Button)findViewById(R.id.downloadMp3Button);
downloadTxtButton.setOnClickListener(new DownloadTxtListener());
downloadMp3Button.setOnClickListener(new DownloadMp3Listener()); /*if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}*/
} class DownloadTxtListener implements OnClickListener
{
@Override
public void onClick(View v) {
System.out.println("txt");
HttpDownloader httpDownloader=new HttpDownloader();
String lrc=httpDownloader.download("http://www.cnblogs.com/zhuawang/p/3648551.html");
System.out.println(lrc);
}
} class DownloadMp3Listener implements OnClickListener
{
@Override
public void onClick(View v) {
HttpDownloader httpDownloader=new HttpDownloader();
int ret=httpDownloader.downFile("http://www.cnblogs.com/zhuawang/p/3648551.html","voa/","a.html");
System.out.println(ret);
}
} @Override
public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
} @Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
} /**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment { public PlaceholderFragment() {
} @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
} }
4.设置权限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mars_1500_download"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.mars_1500_download.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<!-- 访问网络权限 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- SD卡访问权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>
6.进linux系统查看文件
adb shell ls -l cd sdcard
Android之访问下载文件的更多相关文章
- Android利用Http下载文件
Android利用Http下载文件 一.场景 下载存文本文件和下载如mp3等大容量的文件 界面 二.代码编写 1.AndroidMainfest.xml中配置 主要是解决网络权限和写SDCard的权限 ...
- 7-STM32物联网开发WIFI(ESP8266)+GPRS(Air202)系统方案升级篇(TCP实现HTTP访问下载文件,明白底层如何实现的,地基稳才踏实)
看了好多文章.....唉,还是自己亲自动手用网络监控软件测试吧 先看这个节安装WEB服务器.....安装好以后就可以用HTTP访问电脑文件了 6-STM32物联网开发WIFI(ESP8266)+GPR ...
- 教你如何在 Android 使用多线程下载文件
# 教你如何在 Android 使用多线程下载文件 前言 在 Android 日常开发中,我们会经常遇到下载文件需求,这里我们也可以用系统自带的 api DownloadManager 来解决这个问题 ...
- Android 通过SOCKET下载文件的方法
本文实例讲述了Android通过SOCKET下载文件的方法.分享给大家供大家参考,具体如下: 服务端代码 import java.io.BufferedInputStream; import java ...
- android:http下载文件并保存到本地或SD卡
想把文件保存到SD卡中,一定要知道SD卡的路径,获取SD卡路径: Environment.getExternalStorageDirectory() 另外,在保存之前要判断SD卡是否已经安装好,并且可 ...
- Android OkHttp + Retrofit 下载文件与进度监听
本文链接 下载文件是一个比较常见的需求.给定一个url,我们可以使用URLConnection下载文件. 使用OkHttp也可以通过流来下载文件. 给OkHttp中添加拦截器,即可实现下载进度的监听功 ...
- android多线程断点续传下载文件
一.目标 1.多线程抢占服务器资源下载. 2.断点续传. 二.实现思路. 假设分为三个线程: 1.各个线程分别向服务器请求文件的不同部分. 这个涉及Http协议,可以在Header中使用Range参数 ...
- android NDK的下载-文件太大
需要FQ,建议使用VPN,下载前准备点时间配置网络环境.我的百度网盘好像有~~不过忘记地址了,改天共享,或者私聊我. 2015.4 Android 5.1 Android Studio https:/ ...
- Android根据URL下载文件保存到SD卡
//下载具体操作 private void download() { try { URL url = new URL(downloadUrl); //打开连接 URLConnection conn = ...
随机推荐
- Java Warmup
http://www.brendangregg.com/blog/2016-09-28/java-warmup.html
- 使用Ef时,对一个或多个实体的验证失败。有关详细信息,请参见“EntityValidationErrors”属性。
EntityValidationErrors 关于如何查看 EntityValidationErrors 详细信息的解决方法 我们在 EF 的编程中,有时候会遇到这样一个错误: 但是,按照他的提示 ...
- 在Discuz中增加创始人
第一步 在 /config/config_uccenter.php 中 修改 $_config['admincp']['founder'] = '用户UID,用户UID2'; 第二步 在 UPDA ...
- nginx-gridfs使用
安装nginx及nginx-gridfs 依赖库.工具 # yum -y install pcre-devel openssl-devel zlib-devel # yum -y install ...
- spring基于注解的配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...
- 关于ttserver, mongodb, couchbase. ssdb ,tair, leveldb的一点使用体验
2年前使用的ttserver,性能很高,支持分布式,但稳定性不足,当存储容量达到亿级的时间经常会出现无法插入的情况,而且不知道是什么原因造成的错误,重启后也无济于事,只好重启开新库. 单库写入性能 2 ...
- apache commons vfs 文件夹监控
package test.vfs; import java.io.File; import org.apache.commons.logging.Log; import org.apache.comm ...
- Hive(七):HQL DML
HQL DML 主要涉到对Hive表中数据操作,包含有:load.INSERT.DELETE.EXPORT and IMPORT,详细资料参见:https://cwiki.apache.org/con ...
- 【extjs】 ext5 Ext.grid.Panel 分页,搜索
带有分页,搜索的grid. <%@page language="java" contentType="text/html; charset=UTF-8" ...
- nginx ssi 配置小细节(一)
最近工作需要使用nginx的ssi (server side include)技术,在这里,将使用中的一点心得分享一下,也是一种备忘! 首先,nginx的ssi启用很简单,就只有三个最基本的指令: s ...