关于下载文件封装的两个类(Mars)
首先是文件FileUtils.java
package mars.utils; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List; import mars.model.Mp3Info;
import android.os.Environment; public class FileUtils {
private String SDCardRoot; public FileUtils() {
// 得到当前外部存储设备的目录
SDCardRoot = Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ File.separator;
} /**
* 在SD卡上创建文件
*
* @throws IOException
*/
public File createFileInSDCard(String fileName, String dir)
throws IOException {
File file = new File(SDCardRoot + dir + File.separator + fileName);
System.out.println("file---->" + file);
file.createNewFile();
return file;
} /**
* 在SD卡上创建目录
*
* @param dirName
*/
public File creatSDDir(String dir) {
File dirFile = new File(SDCardRoot + dir + File.separator);
System.out.println(dirFile.mkdirs());
return dirFile;
} /**
* 判断SD卡上的文件夹是否存在
*/
public boolean isFileExist(String fileName, String path) {
File file = new File(SDCardRoot + path + File.separator + 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 = createFileInSDCard(fileName, path);
output = new FileOutputStream(file);
byte buffer[] = new byte[4 * 1024];
int temp;
while ((temp = input.read(buffer)) != -1) {
output.write(buffer, 0, temp);
}
output.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return file;
} }
然后是下载的HttpDownload.java
package mars.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; import mars.utils.FileUtils; 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) {
e.printStackTrace();
} finally {
try {
buffer.close();
} catch (Exception e) {
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(fileName,path)) {
return 1;
} else {
inputStream = getInputStreamFromUrl(urlStr);
File resultFile = fileUtils.write2SDFromInput(path,fileName, inputStream);
if (resultFile == null) {
return -1;
}
}
} catch (Exception e) {
e.printStackTrace();
return -1;
} finally {
try {
inputStream.close();
} catch (Exception e) {
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;
}
}
注意使用的时候需要添加相应的权限,还有需要开辟新的线程,以为安卓不能在主线程中执行耗时的操作(比如:下载文件)
下面是我自己写的一个,没什么技术含量,纯给新手测试用用:
package com.example.httpdownload; import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button; public class MainActivity extends Activity {
Button downButton; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
downButton = (Button) findViewById(R.id.button1);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
downButton.setOnClickListener(listener);
} @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;
}
} View.OnClickListener listener = new View.OnClickListener() { public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
Thread thread = new Thread(new MyRunable());
thread.start();
break; default:
break;
}
}
}; private void downLoadFile() {
String urlStr = "http://10.3.19.26:8080/2015-1-6/1.txt";
HttpDownloader httpDownloader = new HttpDownloader();
int result = httpDownloader.downFile(urlStr, "", " 1.txt");
System.out.println("<-------->" + result);
} public class MyRunable implements Runnable { public void run() {
// TODO Auto-generated method stub
downLoadFile();
} }
}
关于下载文件封装的两个类(Mars)的更多相关文章
- Java实现从服务器下载文件到本地的工具类
话不多说,直接上代码...... import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServlet ...
- 可以在一个.java文件中写两个类吗?
一个java文件中可以有任意多个类,接口或是注解..但是只能有一个类是public的,而且这个类的名字要和文件同名,比如public类名为A则文件名就应当为A.java
- Android和FTP服务器交互,上传下载文件(实例demo)
今天同学说他备份了联系人的数据放在一个文件里,想把它存到服务器上,以便之后可以进行下载恢复..于是帮他写了个上传,下载文件的demo 主要是 跟FTP服务器打交道-因为这个东东有免费的可以身亲哈 1. ...
- TFS二次开发05——下载文件(DownloadFile)
前面介绍了怎样读取TFS上目录和文件的信息,怎么建立服务器和本地的映射(Mapping). 本节介绍怎样把TFS服务器上的文件下载到本地. 下载文件可以有两种方式: using Microsoft.T ...
- 本地缓存下载文件,download的二次封装
来源:http://ask.dcloud.net.cn/article/524 源码下载链接 说明: (1)由于平时项目中大量用到了附件下载等功能,所以就花了一个时间,把plus的downlaod进行 ...
- (转)FTP操作类,从FTP下载文件
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Net ...
- .NET两种常见上传下载文件方法
1.FTP模式 代码如下: (1)浏览 /// <summary> /// 浏览文件 /// </summary> /// <param name="tbCon ...
- C# WebClient类上传和下载文件
这篇文章主要介绍了C# WebClient类用法实例,本文讲解使用WebClient下载文件.OpenWriter打开一个流使用指定的方法将数据写入到uri以及上传文件示例,需要的朋友可以参考下 ...
- C++学习笔记一 —— 两个类文件互相引用的处理情况
先记录一些零碎的知识点: 1. 一个类可以被声明多次,但只能定义一次,也就是可以 class B; class B; class B; ……; class B {……}; 这样子. 2. 一个 ...
随机推荐
- dataguard类型转换与模式转化
修改数据保护模式步骤 前提:是否满足转换模式的配置要求 最大保护(Maximum Protection):Standby Database 必须配置Standby Redo Log,Primary D ...
- 转 对APK进行重签名
1. 生成Android APK包签名证书1). 在doc中切换到jdk的bin目录cd C:\Program Files\Java\jdk1.6.0_18\bin2). 运 ...
- ZigBee自组网地址分配与路由协议概述
1. ZigBee简介 ZigBee是基于IEEE802.15.4标准的低功耗局域网协议.根据国际标准规定,ZigBee技术是一种短距离.低功耗的无线通信技术. ZigBee协议从下到上分别为物理层( ...
- typedef 函数指针的用法
转自:http://www.cnblogs.com/shenlian/archive/2011/05/21/2053149.html typedef 函数指针的用法 在网上搜索函数指针,看到一个例子. ...
- SpringMVC前置控制器SimpleUrlHandlerMapping配置
1. <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5&qu ...
- js中全局变量的一点小知识点
js中有三种方式定义全局变量: 在任何函数外面直接执行var语句,例如:var f="value"; 直接添加一个属性到全局变量上,在web浏览器中,全局对象名为window.例如 ...
- Silverlight 5 系列学习之一
最近公司要用Silverlight 开发并且使用了5 ,以前只学过WPF 没看过Silverlight ,不过在争光中国看了看其概念原来如此.它只不过是轻量级的WPF,且目标在于跨浏览器及平台.费话少 ...
- 读取web应用下的资源文件(例如properties)
package gz.itcast.b_resource; import java.io.IOException; import java.io.InputStream; import java.ut ...
- 【网络爬虫】【python】网络爬虫(五):scrapy爬虫初探——爬取网页及选择器
在上一篇文章的末尾,我们创建了一个scrapy框架的爬虫项目test,现在来运行下一个简单的爬虫,看看scrapy爬取的过程是怎样的. 一.爬虫类编写(spider.py) from scrapy.s ...
- Regex Golf 练习记录
正则表达式的练习网站:https://alf.nu/RegexGolf 共17道题:只能说从第10题开始就很变态了,就是看看答案好了 .Warmup: foo .Anchors: k$ 或 ick$ ...