/**
* AsyncHttpClient 是自定义的一个工具类 用于存放downloadStream下载方法的
* 总体思路就是 先得到手机的一个目录 然后建一个文件夹 往里写数据流
**/
AsyncHttpClient client= new AsyncHttpClient();
/**
*创建本地文件 CommonUtil是我存放方法的地方 getRootFilePath方法我放到下面了
*自己 找地方放 然后把CommonUtil改成自己的
**/
String pPath = CommonUtil.getRootFilePath();
//DATA_CACHE_PATH自己写的目录
String fileDir = pPath + Constants.DATA_CACHE_PATH;
File file = new File(fileDir);
if (!file.exists()) {
file.mkdir();
}
String s = orderID+mDatalist.get(position).getFileName();
File f = new File(file.getAbsolutePath(), s);
if (!f.exists()) {
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
// client.downloadFile(url,null,s,AttachmentActivity.this);
client.downloadStream(url,f.getAbsolutePath(),null);
这上面是使用的地方用的代码 下面的代码找个地方放就可以 是具体的方法
//这个就是下载数据流的方法了
public boolean downloadStream(String url, String filePath, String content) {
URL u = null;
boolean rtn = false;
FileOutputStream output = null;
InputStream is = null;
try {
u = new URL(url);
HttpURLConnection connection = null;
connection = (HttpURLConnection) u.openConnection();
connection.setRequestProperty("connection", "Keep-Alive");
// connection.setRequestMethod("POST");
connection.setUseCaches(false);
// connection.setRequestProperty("Content-Type",
// "application/json");
// connection.setDoInput(true);
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
// connection.setDoOutput(true);
connection.connect();
if (!TextUtils.isEmpty(content)) {
OutputStream outputStream = connection.getOutputStream();
outputStream.write(content.getBytes());
outputStream.close();
}
File wdFile = new File(filePath);
output = new FileOutputStream(wdFile);
is = connection.getInputStream();
connection.getContentLength();
byte data[] = new byte[1024];
int count = 0;
while ((count = is.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
rtn = true;
}
catch (Exception e) {
rtn = false;
e.printStackTrace();
}
finally {
try {
if (is == null) {
return false;
} else {
output.close();
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return rtn;
}
//找到手机中内置存储卡的根目录
public static String getRootFilePath() {
if (hasSDCard()) {
return Environment.getExternalStorageDirectory().getAbsolutePath()
+ "";
} else {
return Environment.getDataDirectory().getAbsolutePath() + "/data";
}
}
//上面需要判断用的方法
public static boolean hasSDCard() {
String status = Environment.getExternalStorageState();
if (!status.equals(Environment.MEDIA_MOUNTED)) {
return false;
}
return true;
}