一、文件下载的步骤
1.创建一个HttpURLConnection对象
url
=
new
URL(urlStr);
HttpURLConnection urlConn = (HttpURLConnection)
url
.openConnection();
2.获得一个InputStream对象 urlConn.getInputStream( )
//A.直接得到InputStream
InputStream inputStream = urlConn.getInputStream();
//B 得到String
buffer =
new
BufferedReader(
new
InputStreamReader(
urlConn.getInputStream()));
while
( (line = buffer.readLine()) !=
null
)
{
sb.append(line);
}
3.访问网络的权限 android.permission.INTERNET
<
uses-permission
android:name
=
"android.permission.INTERNET"
/>
HttpDownloader.java
EXP:
/**
* 根据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;
}
二、下载到SD卡里
1.得到当前设备SD卡的目录 Environment.getExternalStorageDirectory();
SDPATH
= Environment. getExternalStorageDirectory() + File.
separator
;
//"/";
2.访问SD卡的权限 android.permission.WRITE_EXTERNAL_STORAGE
<
uses-permission
android:name
=
"android.permission.WRITE_EXTERNAL_STORAGE"
/>
FIleUtils.java
//在SD卡创建文件
public File creatSDFile(String fileName) throws IOException
{
File file = new File (SDPATH + fileName);
file.createNewFile();
return file;
}
//将一个InputStream里面的数据写入SD卡中
public File write2SDFromInput(String path,String fileName,InputStream input)
{
File file = null;
OutputStream output = null;
try {
creatSDDir(path);
file = creatSDFile(path+File.separator +fileName);
output = new FileOutputStream(file);
byte buffer [] = new byte[4 * 1024];
int temp;
while((temp = input.read(buffer)) != -1)
{
output.write(buffer,0,temp);
//写入流,写入开始,写入长度;读取流的时候,读取多少length 写多少length,难道的文件长度 都刚好是 4*1024的整数倍?
}
output.flush();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
Log. e(TAG , "写入SD卡出错" );
System. out.println( "-----------写入SD卡出错-----------" );
} finally{
try {
output.close();
} catch (Exception e) {
// : handle exception
e.printStackTrace();
}
}
return file;
}
三、说明项目如何使用
打开tomcat,查看分配的地址;
android 4.0 以上开始不允许在主线程下载文件,于是新开线程来下载
new Thread(){
public void run(){
HttpDownloader downloader = new HttpDownloader();
int result = downloader.downFile("http://192.168.1.107:8080/MP3/creep.mp3" ,"MPPP3", "creep.mp3" );
System. out.println(result);
}
}.start();
源文件项目
HttpDownloader.java
public
class
HttpDownloader
{
String
TAG
=
"HttpDownloader"
;
private
URL
url
=
null
;
/*根据URL下载文件,前提是这个文件当中的内容是文本,
函数的返回值就是文件中的内容
@param urlstr
@return string*/
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) {
//
TODO
: handle exception
e.printStackTrace();
System.
out
.println(
"下载歌词失败"
);
}
finally
{
try
{
buffer.close();
}
catch
(Exception e2) {
//
TODO
: handle exception
e2.printStackTrace();
}
}
System.
out
.println(
"开始下载LRC文件"
);
System.
out
.println(
"-------------"
+sb.toString());
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+File.
separator
+fileName))
{
System.
out
.println(
"文件已存在"
);
return
1;
}
else
{
inputStream = getInputStreamFromUrl(urlStr);
File resultFile = fileUtils.write2SDFromInput(path, fileName, inputStream);
if
(resultFile ==
null
)
{
System.
out
.println(
"写入失败"
);
return
-1;
}
}
}
catch
(Exception e) {
//
TODO
: handle exception
e.printStackTrace();
System.
out
.println(
"下载歌曲异常、失败"
);
return
-1;
}
finally
{
try
{
inputStream.close();
}
catch
(Exception e) {
//
TODO
: handle exception
e.printStackTrace();
}
}
System.
out
.println(
"下载歌曲成功0"
);
return
0;
}
/*
根据URL得到输入流
*/
public
InputStream getInputStreamFromUrl(String urlStr)
throws
MalformedURLException, IOException
{
url
=
new
URL(urlStr);
HttpURLConnection urlConn = (HttpURLConnection)
url
.openConnection();
InputStream inputStream = urlConn.getInputStream();
return
inputStream;
}
}
FIleUtils.java
public
class
FileUtils
{
String
TAG
=
"FILEUTILS"
;
private
String
SDPATH
;
public
String getSDPATH() {
return
SDPATH
;
}
public
FileUtils() {
//得到当前外部储存设备的目录
super
();
SDPATH
= Environment. getExternalStorageDirectory() + File.
separator
;
//"/";
}
//在SD卡创建文件
public
File creatSDFile(String fileName)
throws
IOException
{
File file =
new
File(
SDPATH
+ fileName);
file.createNewFile();
return
file;
}
//在SD卡创建目录
public
File creatSDDir(String dirName)
throws
IOException
{
File dir =
new
File(
SDPATH
+ dirName);
dir.mkdir();
return
null
;
}
//判断文件是否存在
public
boolean
isFileExist (String fileName)
{
File file =
new
File(
SDPATH
+ 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 = creatSDFile(path+File.
separator
+fileName);
output =
new
FileOutputStream(file);
byte
buffer [] =
new
byte
[4 * 1024];
int
temp;
while
((temp = input.read(buffer)) != -1)
{
output.write(buffer,0,temp);
//写入流,写入开始,写入长度;读取流的时候,读取多少length 写多少length,难道的文件长度 都刚好是 4*1024的整数倍?
}
output.flush();
}
catch
(Exception e) {
//
TODO
: handle exception
e.printStackTrace();
Log. e(
TAG
,
"写入SD卡出错"
);
System.
out
.println(
"-----------写入SD卡出错-----------"
);
}
finally
{
try
{
output.close();
}
catch
(Exception e) {
// : handle exception
e.printStackTrace();
}
}
return
file;
}
}
DownerActivity.java
public
class
DownerActivity
extends
Activity {
private
Button
downloadMp3Bt
;
private
Button
downloadLrcBt
;
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.
activity_fullscreen
);
downloadMp3Bt
= (Button) findViewById(R.id.
downloadmp3bt
);
downloadMp3Bt
.setOnClickListener(
new
DownloadMp3Listener());
downloadLrcBt
= (Button) findViewById(R.id.
downloadlrcbt
);
downloadLrcBt
.setOnClickListener(
new
DownloadLrcListener());
}
class
DownloadMp3Listener
implements
OnClickListener
{
@Override
public
void
onClick(View v) {
new
Thread(){
public
void
run(){
HttpDownloader downloader =
new
HttpDownloader();
int
result = downloader.downFile(
"http://192.168.1.107:8080/MP3/creep.mp3"
,
"MPPP3"
,
"creep.mp3"
);
System.
out
.println(result);
}
}.start();
Toast. makeText(getApplicationContext(),
"开始下载MP3文件"
, Toast.
LENGTH_SHORT
).show();
}
}
class
DownloadLrcListener
implements
OnClickListener
{
@Override
public
void
onClick(View v) {
//
TODO
Auto-generated method stub
new
Thread(){
public
void
run(){
HttpDownloader downloader =
new
HttpDownloader();
String xml = downloader.download(
"http://192.168.1.107:8080/MP3/mettingAngel.lrc"
);
downloader.downFile(
"http://192.168.1.107:8080/MP3/mettingAngel.lrc"
,
"MPPP3"
,
"mettingAngel.txt"
);
// System.out.println("-------------"+ xml);
// Toast.makeText(getApplicationContext(), "开始下载LRC文件", Toast.LENGTH_SHORT).show();
}
}.start();
Toast. makeText(getApplicationContext(),
"开始下载LRC文件"
, Toast.
LENGTH_SHORT
).show();
}
}
@Override
public
boolean
onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.
fullscreen
, menu);
return
true
;
}
}