安卓下载保存到本地(二)

来源:互联网 发布:UNetbootin ubuntu 编辑:程序博客网 时间:2024/06/11 14:09
/*
* 该函数返回整形-1:代表下载文件出错。
* 0:代表下载文件成功
* 1:代表下载文件经存在
*/
public int downLoadFile(String urlStr,String path,String fileName){
InputStream inputStream=null;
URL url;
GoToSDCard gotoSDCard=new GoToSDCard();
if(gotoSDCard.isFileExist(path+fileName)){
return 1;
}else{
try {
url=new URL(urlStr);
HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();
inputStream=urlConn.getInputStream(); 
File resultFile=gotoSDCard.write2SDFromInput(path, fileName,inputStream);//将数据流保存到SD卡当中
if(resultFile==null){
return -1;
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();}
}
}
return 0;
}

public class GoToSDCard {

private String SDPATH=null;

public String getSDPATH(){
return SDPATH; 
}

public GoToSDCard(){
//得到当前外部存储设备的目录
// SDCARD
SDPATH=Environment.getExternalStorageDirectory()+"/";
System.out.println("SDPATH="+SDPATH);
}



/*
*在SD卡上创建文件 
*/
public File CreatSDFile(String fileNmae){
File file =new File(SDPATH+fileNmae);
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return file;
}
/*
* 在SD卡上创建目录
*/
public File creatSDDir(String dirName){

File dir=new File(SDPATH+dirName);
if(!dir.exists()){
dir.mkdirs();
}
return dir;
}
/*
*判断SD卡上的文件夹是否存在
*/
public boolean isFileExist(String fileName){
File file =new File(SDPATH+fileName);
return file.exists();
}
/*
*将一个InputSteam里面的数据写入到SD卡中 
*/
public File write2SDFromInput(String path,String fileName,InputStream input){
System.out.println("path="+path+";fileName="+fileName+";");
File file =null;
File folder=null;
OutputStream output=null;
try {
folder=creatSDDir(path);
System.out.println("folder="+folder);
file=CreatSDFile(path+fileName);
System.out.println("file="+file);
output=new FileOutputStream(file);
byte buffer[]=new byte[4*1024];
while((input.read())!=-1){
output.write(buffer);
}
output.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try{
output.close();
}catch(Exception e){
e.printStackTrace();
}
}
return file;
}

}


0 0
原创粉丝点击