首先是文件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. Excel 2007无法打开多个窗口的问题

    Excel 2007使用的时候打开多个工作薄的时候,不像2003那样默认独立分开窗口显示.要切换工作簿,需要通过 “视图-切换窗口”来选择需要当前活动的窗口,这样的操作给同时操作多个工作薄来说,非常不 ...

  2. poj3281Dining——网络流匹配

    题目:http://poj.org/problem?id=3281 网络流做图中的匹配,注意为了限制每头牛只匹配一种食物和一种饮料,要把牛拆成两个点,之间连边权为1的边. 代码如下: #include ...

  3. Enum定义位域, 即可以通过位操作来产生未命名的值

    通过FlagsAttribute可以实现. // A bit field or flag enumeration of harvesting seasons. [Flags] public enum ...

  4. maven+eclpse+jmeter+jenkis

    1.maven配置:http://www.cnblogs.com/AlanLee/p/6133189.html 2.在eclipse中创建maven项目:https://jingyan.baidu.c ...

  5. Elasticsearch集成ik分词器

    1.插件地址https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.0.0/elasticsearch-anal ...

  6. Jquery.ajax 详细解释 通过Http请求加载远程数据

    首先请看一个Jquery.ajax的例子 $.ajax({ type: "GET", url: "/api/SearchApi/GetResults", dat ...

  7. 9. 那些强悍的PHP一句话后门

    强悍的PHP一句话后门 这类后门让网站.服务器管理员很是头疼,经常要换着方法进行各种检测,而很多新出现的编写技术,用普通的检测方法是没法发现并处理的.今天我们细数一些有意思的PHP一句话木马. 利用4 ...

  8. oracle查看表,索引,视图,存储过程的定义

    通过  DBMS_METADATA  包 Oracle 的在线文档,对这个包有详细说明: DBMS_METADATA 通过该dbms_metadata包的get_ddl()方法,我们可以查看表,索引, ...

  9. “MVC+Nhibernate+Jquery-EasyUI”信息发布系统 第一篇

    一.第一篇内容中必须得简单的介绍一下MVC(在大学时用的是WebForm,拖控件感觉很爽,但是工作后,技术总监让一定要放弃这种 想法!) 1.MVC是什么?:(1) ASP.NET MVC是微软官方提 ...

  10. cassandra的命令

    cassandra的命令: connect <hostname>/<port> (<username> '<password>')?;    Conne ...