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 = ...
随机推荐
- ps白平衡
ps白平衡:在正常光线下看起来是白颜色的东西在有色光或者较暗的光线下看起来可能就不是白色,还有荧光灯下的"白"也是"非白".对于这一切如果能调整白平衡,则在所得 ...
- UIview 学习与自定义--ios
UIView *view1=[[UIView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)]; view1.backgroundColor=[UI ...
- 单例模式-ios
#import <Foundation/Foundation.h> @interface UserContext : NSObject <NSCopying> @propert ...
- 归档-ios
/****普通对象归档**/ NSString *homePath=NSHomeDirectory(); NSString *fileName=@"test.vse"; NSStr ...
- mybatis 批量插入和where条件使用
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-/ ...
- myBatis 参数配置
关于参数的类型 有四种类型: http://www.07net01.com/zhishi/402787.html 以上链接有所介绍,四种类型有:单个参数.多个参数.Map封装参数.List封装IN 如 ...
- WITH SCHEMABINDING
SCHEMABINDING 选项,防止视图所引用的表在视图未被调整的情况下发生改变的选项. 也就是说,一旦视图被指定了WITH SCHEMABINDING 选项,那么,在修改用于 ...
- eclipse报An error has occurred,See error log for more details. java.lang.NullPointerException错误
eclipse报An error has occurred,See error log for more details. java.lang.NullPointerException错误,解决办法: ...
- Java连接Oracle
Process myProcess = Runtime.getRuntime().exec("ipconfig"); InputStreamReader ir = new Inpu ...
- WCF学习心得----(四)服务承载
WCF学习心得----(四)服务承载 这一章节花费了好长的时间才整理个大概,主要原因是初次接触这个东西,在做练习实践的过程中,遇到了很多的问题,有些问题到目前还没有得以解决.所以在这一章节中,有一个承 ...