首先是文件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)的更多相关文章

  1. Java实现从服务器下载文件到本地的工具类

    话不多说,直接上代码...... import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServlet ...

  2. 可以在一个.java文件中写两个类吗?

    一个java文件中可以有任意多个类,接口或是注解..但是只能有一个类是public的,而且这个类的名字要和文件同名,比如public类名为A则文件名就应当为A.java

  3. Android和FTP服务器交互,上传下载文件(实例demo)

    今天同学说他备份了联系人的数据放在一个文件里,想把它存到服务器上,以便之后可以进行下载恢复..于是帮他写了个上传,下载文件的demo 主要是 跟FTP服务器打交道-因为这个东东有免费的可以身亲哈 1. ...

  4. TFS二次开发05——下载文件(DownloadFile)

    前面介绍了怎样读取TFS上目录和文件的信息,怎么建立服务器和本地的映射(Mapping). 本节介绍怎样把TFS服务器上的文件下载到本地. 下载文件可以有两种方式: using Microsoft.T ...

  5. 本地缓存下载文件,download的二次封装

    来源:http://ask.dcloud.net.cn/article/524 源码下载链接 说明: (1)由于平时项目中大量用到了附件下载等功能,所以就花了一个时间,把plus的downlaod进行 ...

  6. (转)FTP操作类,从FTP下载文件

    using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Net ...

  7. .NET两种常见上传下载文件方法

    1.FTP模式 代码如下: (1)浏览 /// <summary> /// 浏览文件 /// </summary> /// <param name="tbCon ...

  8. C# WebClient类上传和下载文件

    这篇文章主要介绍了C# WebClient类用法实例,本文讲解使用WebClient下载文件.OpenWriter打开一个流使用指定的方法将数据写入到uri以及上传文件示例,需要的朋友可以参考下   ...

  9. C++学习笔记一 —— 两个类文件互相引用的处理情况

    先记录一些零碎的知识点: 1. 一个类可以被声明多次,但只能定义一次,也就是可以 class B;  class B;  class B; ……;  class B {……};  这样子. 2. 一个 ...

随机推荐

  1. unicode和utf-8互转

    1.1 ASCII码 我们知道, 在计算机内部, 所有的信息最终都表示为一个二进制的字符串. 每一个二进制位(bit)有0和1两种状态, 因此八个二进制位就可以组合出 256种状态, 这被称为一个字节 ...

  2. Wmware Player中Linux挂载U盘

    菜单(Player)中有一项是可移动设备,中选择U盘,然后选择连接(断开主机), 然后在命令行中敲入 fdisk -l 正常情况下是sda是硬盘的信息,然后将会看到一个单蹦的sdb4的信息(sdb4可 ...

  3. Nuget-QRCode:jquery-qrcode

    ylbtech-Nuget-QRCode:jquery-qrcode 1.返回顶部 1. <!DOCTYPE html> <html> <head> <tit ...

  4. JavaScript总结(1)

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/stri ...

  5. openstack 创建镜像生成虚拟机不知道密码如何解决

    背景: openstack juno版本,使用glance创建centos7镜像,然后生成虚拟机. 操作步骤: 首先获取镜像http://cloud.centos.org/centos/7/image ...

  6. FZU - 2218 Simple String Problem(状压dp)

    Simple String Problem Recently, you have found your interest in string theory. Here is an interestin ...

  7. Eclipse与IntelliJ IDEA区别

    1.没有workspace,新增modules(Workspace-Project,Project-Module) 2.没有perspectives,自动根据上下文调用相关工具 3.没有保存按钮,自动 ...

  8. GitBook 入门学习

    一.什么是 Gitbook GitBook 是一个基于 Node.js 的命令行工具,支持 Markdown 和 AsciiDoc 两种语法格式,可以输出 HTML.PDF.eBook 等格式的电子书 ...

  9. 火狐浏览器httprequest插件添加和使用方法(适用于前后台分离,测试后台接口)

    第一步:打开火狐浏览器工具栏找到添加组件 1.如图1点击添加组件 第二步:添加组件Httprequest 1.如图2,检索Httprequest 2.如图3,将组件添加到火狐浏览器中 3.如图3.5, ...

  10. Search index

    问题:查找字符串b在a中的起始位置,如果b不为a的子串,则返回-1 示例: 输入:a = "well", b = "el"    输出:1 输入:a=" ...