首先是文件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. 重学JAVA基础(一):PATH和CLASSPATH

    我想大多数Java初学者都会遇到的问题,那就是怎么配置环境,执行java -jar xxx.jar  都会报NoClassDefFindError,我在最开始学习的时候,也遇到了这些问题. 1.PAT ...

  2. 开发商应用被App Store拒绝的79个原因

    转自:http://www.gamelook.com.cn/2014/10/186017 作为iOS开发者,估计有很多都遇到过APP提交到App Store被拒,然后这些被拒的原因多种多样,今天小编收 ...

  3. java.lang.ClassCastException:android.widget.Button cannot be cast to android.widget.ImageView

    今天遇到一个错误也不知道怎么回事,上网搜了一下: 出现的问题是:java.lang.ClassCastException:android.widget.Button cannot be cast to ...

  4. asp.net mvc Model验证总结及常用正则表达式【转载】

    关于Model验证官方资料: http://msdn.microsoft.com/zh-cn/library/system.componentmodel.dataannotations.aspx AS ...

  5. [cf2015ICLFinalsDiv1J]Ceizenpok’s formula

    题意:$C_n^m\% k$ 解题关键:扩展lucas+中国剩余定理裸题 #include<algorithm> #include<iostream> #include< ...

  6. App Distribution Guide--(三)---Configuring Your Xcode Project for Distribution

    Configuring Your Xcode Project for Distribution You can edit your project settings anytime, but some ...

  7. VC代码生成里面的/MT /MTd /MD /MDd的意思

    VC代码生成里面的/MT /MTd /MD /MDd的意思. 意思上已经很明白了.但是往往很多人弄不清楚到底怎么选择. /MT是 "multithread, static version ” ...

  8. 《SpringBoot揭秘 快速构建微服务体系》读后感(五)

    应用日志和spring-boot-starter-logging 快速web应用开发与spring-boot-starter-web 1.项目结构层面的约定

  9. C# 生成word 文档 代码 外加 IIS报错解决方案

    using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...

  10. SPFA算法——最短路径

    粗略讲讲SPFA算法的原理,SPFA算法是1994年西南交通大学段凡丁提出 是一种求单源最短路的算法 算法中需要用到的主要变量 int n;  //表示n个点,从1到n标号 int s,t;  //s ...