文件下载的步骤
1.创建一个HttpURLConnection对象:
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
2.获得一个InputStream对象
httpURLConnection .getInputStream();
3.访问(添加)网络的权限
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
获取SD卡的文件路径
Environment.getExternalStorageDirectory();
访问SD卡的权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
package com.yanjun;
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() {
// 获取SD卡的路径
SDPATH = Environment.getExternalStorageDirectory() + "/";
}
/**
* 在SD卡中创建文件
*
*/
public File createSDFile(String fileName) throws IOException {
File file = new File(SDPATH + fileName);
file.createNewFile();
return file;
}
/**
* 在SD卡上创建目录
*
*/
public File createSDDir(String dirName) {
File dirFile = new File(SDPATH, dirName);
dirFile.mkdir();
return dirFile;
}
/**
* 判断SD卡的文件夹是否存在
*/
public boolean isFileExist(String fileName) {
File file = new File(SDPATH + fileName);
return file.exists();
}
/**
* 将一个InputStream数据写入到SD卡中
*
*/
public File writeSDFromInput(String path,String fileName,InputStream inputStream){
File file = null;
//写入数据用outputStream
OutputStream outputStream = null;
try {
//创建文件目录createSDFile()
createSDDir(path);
//创建文件
file = createSDFile(path + fileName);
//针对file对象写入数据outputStream---->4 * 1024即每4K传一次
outputStream = new FileOutputStream(file);
byte buffer[] = new byte[4 * 1024];
while ((inputStream.read(buffer)) != -1) {
outputStream.write(buffer);
}
//调用flush()方法,清空文件缓存
outputStream.flush();
} catch (Exception e) {
// TODO: handle exception
}finally{
try {
//关闭
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return file;
}
}
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() {
// 获取SD卡的路径
SDPATH = Environment.getExternalStorageDirectory() + "/";
}
/**
* 在SD卡中创建文件
*
*/
public File createSDFile(String fileName) throws IOException {
File file = new File(SDPATH + fileName);
file.createNewFile();
return file;
}
/**
* 在SD卡上创建目录
*
*/
public File createSDDir(String dirName) {
File dirFile = new File(SDPATH, dirName);
dirFile.mkdir();
return dirFile;
}
/**
* 判断SD卡的文件夹是否存在
*/
public boolean isFileExist(String fileName) {
File file = new File(SDPATH + fileName);
return file.exists();
}
/**
* 将一个InputStream数据写入到SD卡中
*
*/
public File writeSDFromInput(String path,String fileName,InputStream inputStream){
File file = null;
//写入数据用outputStream
OutputStream outputStream = null;
try {
//创建文件目录createSDFile()
createSDDir(path);
//创建文件
file = createSDFile(path + fileName);
//针对file对象写入数据outputStream---->4 * 1024即每4K传一次
outputStream = new FileOutputStream(file);
byte buffer[] = new byte[4 * 1024];
while ((inputStream.read(buffer)) != -1) {
outputStream.write(buffer);
}
//调用flush()方法,清空文件缓存
outputStream.flush();
} catch (Exception e) {
// TODO: handle exception
}finally{
try {
//关闭
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return file;
}
}
package com.yanjun;
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;
/**
* @author YanJun 根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文本当中的内容。 1.创建一个URL对象
* 2.通过URL创建HttpURLConnection对象 3.得到InputStream 4.从InputStream当中读取数据
*
*/
public class HttpDownLoad {
private URL url = null;
public String download(String urlString) {
// 该方法适合下载任何形式的文本文件
// 声明相关对象
StringBuffer sb = new StringBuffer();
String line = null;
BufferedReader bufferedReader = null;
try {
url = new URL(urlString);// 将下载文件的地址作为参数传进去
// 创建一个Http连接
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
// 使用IO流读取数据
bufferedReader = new BufferedReader(new InputStreamReader(
httpURLConnection.getInputStream()));
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
bufferedReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
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)) {
//判断文件名是否在SD卡中已经存在
System.out.println("文件已经存在");
return 1;
} else {
inputStream = getInputStreamFromUrl(urlStr);
File resultFile = fileUtils.writeSDFromInput(path, fileName,
inputStream);
if (resultFile == null) {
return -1;
}
}
} catch (Exception e) {
return -1;
}finally{
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return 0;
}
/**
* 根据URL得到输入流,将三个步骤封装到getInputStreamFromUrl()函数中
* @param urlStr
* @return
* @throws MalformedURLException
* @throws IOException
*/
public InputStream getInputStreamFromUrl(String urlStr)throws MalformedURLException ,IOException{
url = new URL(urlStr);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
return inputStream;
}
}
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;
/**
* @author YanJun 根据URL下载文件,前提是这个文件当中的内容是文本,函数的返回值就是文本当中的内容。 1.创建一个URL对象
* 2.通过URL创建HttpURLConnection对象 3.得到InputStream 4.从InputStream当中读取数据
*
*/
public class HttpDownLoad {
private URL url = null;
public String download(String urlString) {
// 该方法适合下载任何形式的文本文件
// 声明相关对象
StringBuffer sb = new StringBuffer();
String line = null;
BufferedReader bufferedReader = null;
try {
url = new URL(urlString);// 将下载文件的地址作为参数传进去
// 创建一个Http连接
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
// 使用IO流读取数据
bufferedReader = new BufferedReader(new InputStreamReader(
httpURLConnection.getInputStream()));
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
bufferedReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
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)) {
//判断文件名是否在SD卡中已经存在
System.out.println("文件已经存在");
return 1;
} else {
inputStream = getInputStreamFromUrl(urlStr);
File resultFile = fileUtils.writeSDFromInput(path, fileName,
inputStream);
if (resultFile == null) {
return -1;
}
}
} catch (Exception e) {
return -1;
}finally{
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return 0;
}
/**
* 根据URL得到输入流,将三个步骤封装到getInputStreamFromUrl()函数中
* @param urlStr
* @return
* @throws MalformedURLException
* @throws IOException
*/
public InputStream getInputStreamFromUrl(String urlStr)throws MalformedURLException ,IOException{
url = new URL(urlStr);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
return inputStream;
}
}
package com.yanjun;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
Button filmButton;
Button mp3Button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
filmButton = (Button) findViewById(R.id.button_film);
mp3Button = (Button) findViewById(R.id.button_mp3);
filmButton.setOnClickListener(new filmListenner());
mp3Button.setOnClickListener(new mp3Listenner());
}
class filmListenner implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
HttpDownLoad httpDownLoad = new HttpDownLoad();
String fileString = httpDownLoad.download("网址");
System.out.println(fileString);
}
}
class mp3Listenner implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
HttpDownLoad httpDownLoad = new HttpDownLoad();
int result = httpDownLoad.downFile("urlStr", "path", "fileName");
System.out.println(result);
}
}
}
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
Button filmButton;
Button mp3Button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
filmButton = (Button) findViewById(R.id.button_film);
mp3Button = (Button) findViewById(R.id.button_mp3);
filmButton.setOnClickListener(new filmListenner());
mp3Button.setOnClickListener(new mp3Listenner());
}
class filmListenner implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
HttpDownLoad httpDownLoad = new HttpDownLoad();
String fileString = httpDownLoad.download("网址");
System.out.println(fileString);
}
}
class mp3Listenner implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
HttpDownLoad httpDownLoad = new HttpDownLoad();
int result = httpDownLoad.downFile("urlStr", "path", "fileName");
System.out.println(result);
}
}
}
转载于:https://blog.51cto.com/haiyuanxi/958093