跟着教程学习MP3播放器编写,实现了从自己搭建的服务器下载MP3文件,并播放的功能,但是遇到一个问题,我的下载程序的代码在运行时,下载a01.mp3、a01.jpg、a01.gif、a01.txt等文件都可以正常下载,唯独下载a01.lrc文件时出现异常,下载失败。但如果把a01.lrc文件名改为a01.txt,就可以下载成功,实在找不出问题原因了,请大家帮忙,必结贴!
代码如下:
负责下载的线程的代码:mp3Name的值赋为01.mp3、a01.jpg、a01.gif、a01.txt等文件都可以正常下载,唯独下载a01.lrc文件时出现异常。
class DownloadThread implements Runnable {
private Mp3Info mp3Info = null;
public DownloadThread(Mp3Info mp3Info) {
this.mp3Info = mp3Info;
}
@Override
public void run() {
// 下载地址http://192.168.1.102/testWeb/歌曲名
// 根据MP3文件的名字,生成下载地址
//String mp3Name = mp3Info.getMp3Name();
//String mp3Name = "a04.lrc";
String mp3Name="";
try {
mp3Name = URLEncoder.encode("a04.lrc","UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String mp3Url = mp3url_head + URLEncoder.encode(mp3Name);
// //生成下载文件所用的对象
// HttpDownloader httpDownloader = new HttpDownloader();
// 将文件下载下来,并存储到SDCard中
int result = httpDownloader.downFile(mp3Url, mp3Path, URLEncoder.encode(mp3Name));
String resultMessage = null;
if (result == -1) {
resultMessage = mp3Name + "下载失败";
cancelled = true;
} else if (result == 1) {
resultMessage = mp3Name + "已存在,无需重复下载";
cancelled = true;
} else if (result == 0) {
resultMessage = mp3Name + "下载成功";
}
// 发送特定action的广播
Intent Broadcastintent = new Intent();
Broadcastintent.setAction("android.intent.action.MY_RECEIVER");
Broadcastintent.putExtra("resultMessage", resultMessage);
sendBroadcast(Broadcastintent);
}
}
httpDownloader.downFile代码
/**
* 该函数返回整形 -1:代表下载文件出错 0:代表下载文件成功 1:代表文件已经存在
*/
public int downFile(String urlStr, String path, String fileName) {
InputStream inputStream = null;
try {
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;
}
getInputStreamFromUrl代码
public InputStream getInputStreamFromUrl(String urlStr)
throws MalformedURLException, IOException {
url = new URL(urlStr);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setRequestMethod("GET");
InputStream inputStream = urlConn.getInputStream();
this.lenghtOfFile = urlConn.getContentLength();