Android_利用URL实现下载功能

来源:互联网 发布:csol刀战优化辅助 编辑:程序博客网 时间:2024/05/19 19:43
/**
* 申请访问网络权限
*/
<uses-permission android:name="android.permission.INTERNET"/>


class HttpDownloader{
// 创建URL对象
private URL url;

/**
* 下载文本文件
*/
public String download(String urlStr){
private StringBuffer sb = new StringBuffer();
private String line = null;
private BufferedReader reader = null;

try{
// 创建一个Url连接
url = new URL(urlStr);
// 创建一个Http连接
HttpURLConnection urlConn = (HttpURLConnect) url.openConnection();
// 使用IO流读取数据
reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));


while ( null != (line = reader.readLine() )
{
sb.append(line);
}
} catch(Exception e){
e.printStackTrack();
} finally{
try{
reader.close();
} catch(Exception e){
printStackTrack();
}
}
}

return sb.toString();
}




/** 得到当前设备SD卡的目录 ******************************************
* Environment.getExternalStorageDirectory();

*** 访问SD卡的权限
* android.permission.WRITE_EXTERNAL_STORAGE
********************************************************************/


public String getSDPATH{
return Environment.getExternalStorangeDirectory() + "/";
}

/* 在SD卡上创建文件 */
public File createSDFile(String fileName){
File file = new File(getSDPATH + fileName);
file.createNewFile();
return file;
}

/* 在SD卡上创建目录 */
public File createSDDir(String dirName){
File dir = new File(dirName);
dir.mkDir();
return dir;
}

/* 判断SD卡上的文件是否存在 */
public boolean isFileExist(String fileName){
File file = new File(fileName);
return file.exists();
}

/* 将一个InputStream里面的数据写入到SD卡中 */
public File write2SDFromInput( String dirName, String fileName, InputStream in){
File file = null;
OutputStream output = null;

try{
createSDDir(dirName);
file = createSDFile(dirName + fileName);

output = new OutputStream(file);
Byte [] byte = Byte[4 * 1024];
while ( -1 != in.read(buffer) ){
output.write(buffer);
}
output.flush();

catch (Exception e){
e.printStackTrace();

finally{
try{
out.close;
} catch (Exception e){
e.printStackTrace();
}
}

return file;
}


/**
* 下载Mp3文件
* 返回值: 整型 <-1:下载失败>; <0:下载文件成功>; <1:文件已存在>
* 参数: url, 存储路径, 存储文件名
*/
public int downFile(String urlStr, String path, String fileName){
private InputStream inputStream = null;

try{
if ( isFileExist(path + fileName) ){
return 1;
}
else{
inputStream = getInputStreamFromUrl(urlStr);
File returnFile = write2SDFromInput(path, fileName, inputStream);
}
}
catch(Exception e){
e.printStackTrace();
return -1;
}
finally{
try{
inputStream.close();
} catch(Exception e){
e.printStackTrace();
}
}

return 0;
}

/* 根据URL得到输入流 */
public InputStream getInputStreamFromUrl(String urlStr){
InputStream inputStream = null;

try{
url = new URL(urlStr);
HttpUrlConnection urlConn = (HttpUrlConnect) url.openConnection();
InputStream inputStream = urlConn.getInputStream();
}
catch(Exception e){
e.printStackTrace();
}

return inputStream;
}
0 0
原创粉丝点击