1 文件下载工具类
public class DownloadTool {
private URL url = null;
//返回-1下载文件出错,返回0下载成功,返回1文件已经存在
public int downFile(String urlStr,String path,String fileName){
try {
InputStream is = null;
FileTool filetool = new FileTool();
if(filetool.existSDFile(path+fileName)){
return 1;
}else{
//inputStream = 上个从网络上获得的输入流
is = getInputStreamFromUrl(urlStr);
File resultFile = filetool.write2SDCARDFromInputSteam(path, fileName, is);
if(resultFile==null)return -1;
}
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public InputStream getInputStreamFromUrl(String newUrl){
URL url = null;
HttpURLConnection httpURLConnection = null;
InputStream is = null;
try {
url = new URL(newUrl);
httpURLConnection = (HttpURLConnection)url.openConnection();
is = httpURLConnection.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
}
2 文件处理工具类
public class FileTool {
private static String SDCARD = null;
public static String getCurrentFileName(){
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String newdata = dateFormat.format( now );
return newdata+".png";
}
public static void FileTool() {
SDCARD = Environment.getExternalStorageDirectory() + "/";
}
// 创建一个目录
public static File createSDDir(String dirName) {
File fileDir = new File(SDCARD + dirName);
fileDir.mkdir();
return fileDir;
}
// 创建一个文件;
public static File createSDFile(String fileName) throws IOException {
File file = new File(SDCARD+fileName); //注意在这里一定要加上主目录 SDCARD中,才可以,不然会找不到目录 。
file.createNewFile();
return file;
}
// 判断SD卡上的文件是不是存在;
public static boolean existSDFile(String fileName) {
File file = new File(SDCARD + fileName);
return file.exists();
}
// 将一个流对象写入SDCARD
public static File write2SDCARDFromInputSteam(String path, String fileName,
InputStream is) {
File file = null;
OutputStream os = null;
try {
createSDDir(path);
file = createSDFile(path + fileName);
os = new FileOutputStream(file);
byte[] buffer = new byte[4 * 1024];
while (is.read(buffer) != -1) {
os.write(buffer);
}
os.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
os.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
}