Android下载工具类和json解析例子

package com.kuatang.decode;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;


/**
 * 特殊格式的JSON数据解析实例,被注释部分为一般格式的解析方法。
 * @author KUATANG
 *
 */
public class DecodeJson {
/**
* 定义特殊的JSON格式
*/
private static final String jsonStr = "{data:{snapshort:{fields:['open_px','high_px','low_px'],600570.ss:[47.334, 48.556, 10.88],000001.sz:[11.12, 45.54, 76.656]}}}";

private List<HStockEntity> listEntity = new ArrayList<DecodeJson.HStockEntity>();
/**
* 解析特殊格式的json数据,没有数据冗余
*/
public void decodeSpe(){
//由于集成环境不同,仅适用于Android客户端
try {
JSONObject jsonObject = new JSONObject(jsonStr).getJSONObject("data").getJSONObject("snapshort");
Log.i("jsonObject result ------>", jsonObject.toString());
//{"000001.sz":[11.12,45.54,76.656],"600570.ss":[47.334,48.556,10.88],"fields":["open_px","high_px","low_px"]}
Iterator<String> iteratorKeys = jsonObject.keys();
Log.i("iterator result ------>", iteratorKeys.toString());

List<Object> list = new ArrayList<Object>();
JSONArray fields = jsonObject.getJSONArray("fields");
Log.i("fields result ------>", fields.toString());//["open_px","high_px","low_px"]
for(int i = 0; i < fields.length(); i++){
list.add(i, fields.getString(i));
}
Log.i("list result ------>", list.toString());//[open_px, high_px, low_px]

while(iteratorKeys.hasNext()){
String key = (String) iteratorKeys.next();
Log.i("key result ------>", key.toString());//000001.sz  600570.ss  fields
JSONArray array = jsonObject.getJSONArray(key);
Map<Object, Object> map = new HashMap<Object, Object>();
if(key.equals("fields")){
continue;
} else {
for(int i = 0; i < array.length(); i++){
map.put(list.get(i), array.get(i));
}
HStockEntity entity = new HStockEntity();
entity.setSymbol(key);
entity.setHigh_px(Double.parseDouble(map.get("high_px").toString()));
entity.setLow_px(Double.parseDouble(map.get("low_px").toString()));
entity.setOpen_px(Double.parseDouble(map.get("open_px").toString()));
listEntity.add(entity);
}
}

} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//注意输出结果的顺序与原始json字符串相反
if(!listEntity.isEmpty()){
for(int i = 0; i < listEntity.size(); i++){
double open_px = listEntity.get(i).getOpen_px();
double low_px = listEntity.get(i).getLow_px();
double high_px = listEntity.get(i).getHigh_px();
Log.i("open_px result ------>", String.valueOf(open_px));//11.12  47.334...
Log.i("low_px result ------>", String.valueOf(low_px));//76.656  10.88...
Log.i("high_px result ------>", String.valueOf(high_px));//48.556...
}
}
}

class HStockEntity{
private String symbol;
private double high_px;
private double low_px;
private double open_px;

public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
public double getHigh_px() {
return high_px;
}
public void setHigh_px(double d) {
this.high_px = d;
}
public double getLow_px() {
return low_px;
}
public void setLow_px(double low_px) {
this.low_px = low_px;
}
public double getOpen_px() {
return open_px;
}
public void setOpen_px(double open_px) {
this.open_px = open_px;
}

}

/*
* 一般的数据解析{["":"", "":"", "",""...],["":"", "":"", "",""...],......}
Bundle mBundle = intent.getBundleExtra("bundle");
jsonWeb = mBundle.getString("jsonWeb");
try {


JSONArray jsonArray = new JSONArray(jsonWeb);


for (int i = 0; i < jsonArray.length(); i++) {
// JSONObject jsonObject=(JSONObject)jsonArray.getJSONObject(i);
JSONObject jsonObject = (JSONObject) jsonArray.opt(i);
String deport_id = jsonObject.getString("ID");
list.add(deport_id);
String deport_name = jsonObject.getString("NAME");
listNames.add(deport_name);


}


} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

   Drawable img=list.get(position).getImage();
String name=list.get(position).getName();
String price=list.get(position).getPrice();
       */

}


————————————————————————————————————————————————

package com.kuatang.downloader.utils;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;


import android.os.Environment;
/**
 * @description SD存储操作工具类
 * @author KUATANG
 *
 */
public class DownLoaderSDCardUtils {

private String SDCardPath;//根路径

public DownLoaderSDCardUtils(){
this.SDCardPath = Environment.getExternalStorageDirectory() + "/";
}

public String getSDCardPath(){
return SDCardPath;
}

private String getForwardDate(){
//图片文件名时间
Date currementDate = new Date();
SimpleDateFormat format  = new SimpleDateFormat("yyyymmdd_hhmmss");
String forwardDate = format.format(currementDate);
return forwardDate;
}
/**
* @description 调用相机拍照返回图片存储路径
* @param path  "KMVC_ZDGL/"
* @return
*/
public String storeSDPicture(String path){
String IMG_PATH = "";
File file = null;
try {

if(isFileDirectoryExists(path + getForwardDate() + ".jpg")){
return IMG_PATH = "文件已存在";
}else{
createSDCardDirectory(path + getForwardDate() + ".jpg");
file = createSDCardDirectory(path + getForwardDate() + ".jpg");
IMG_PATH = file.getPath().toString();
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e.getMessage());
}

return IMG_PATH;
}

/**
* @description 在SDCARD上创建文件
* @param fileName  
* @return
* @throws IOException
*/
public File createSDCardFile(String path, String fileName) 
throws IOException{
// File file = new File(SDCardPath + fileName);
// file.createNewFile();
String imgPath = SDCardPath + path;
File file = new File(imgPath, fileName);
// file.createNewFile();
return file;
}

/**
* @description 在SDCARD上创建文件目录
* @param fileName  "TZD/"
* @return
* @throws IOException
*/
public File createSDCardDirectory(String fileName) 
throws IOException{
File fileDirectory = new File(SDCardPath + fileName);
fileDirectory.mkdirs();
return fileDirectory;
}

/**
* @description 验证文件夹是否存在
* @param fileName  fileName为文件的路径
* @return
*/
public Boolean isFileDirectoryExists(String fileName){
File file = new File(SDCardPath + fileName);
return file.exists();
}

/**
* @description 将InputStream写入SDCARD中,支持多种形式文件,MP3,图片...
* @param path "TZD/"
* @param fileName  "NAME"
* @param input  "STREAM"
* @return
*/
public File writeSDCardFromInputStream (String path, String fileName, 
InputStream inputStream ){

File file = null;
OutputStream outputStream = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
String imagePath = path + fileName;
try{
boolean isExists = isFileDirectoryExists(imagePath);
if(!isExists){

createSDCardDirectory(path);
}


bis = new BufferedInputStream(inputStream);

file = createSDCardFile(path, fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
int line;

byte buffer[] = new byte[4 * 1024];//每四个字节写一次
while ((line = bis.read(buffer)) != -1){
bos.write(buffer, 0, line);
}

bos.flush();

}catch(Exception e){
e.printStackTrace();
System.out.println(e.getMessage());
}finally{

try{
if(outputStream != null){
outputStream.close();
}
if(fos != null){
fos.close();
}
if(bos != null){
bos.close();
}
if(bis != null){
bis.close();
}

}catch(IOException io){
io.printStackTrace();
System.out.println(io.getMessage());
}
}
return file;
}
}


——————————————————————————————————————————————————————————————

package com.kuatang.downloader.utils;


import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


import android.util.Log;
/**
 * @description HTTP协议下载文件类,text,mp3...
 * @author KUATANG
 *
 */
public class HttpDownLoader {

private URL url = null;
/**
* @description 通过HTTP协议对文本文件进行下载
* @param urlStr 下载地址
* @return
*/
public String downLoadTextFile(String urlStr){

StringBuffer strBuffer = new StringBuffer();
String line = null;
//建立HTTP连接对象
HttpURLConnection httpUrlConn = null;
BufferedReader bufferedReader = null;

try {
url = new URL(urlStr);

try {
httpUrlConn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("HttpURLConnection IOException ------>", e.getMessage());
}

try {
bufferedReader = new BufferedReader(new InputStreamReader(
httpUrlConn.getInputStream()));
while((line = bufferedReader.readLine()) != null){
strBuffer.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.v("System.out.print.sax", e.getMessage() + "downloader exception");
}

} catch (MalformedURLException  mUrlException) {
// TODO Auto-generated catch block
mUrlException.printStackTrace();
Log.e(" URL MalformedURLException IOException ------>", mUrlException.getMessage());
}finally{
try{
if(bufferedReader != null){
bufferedReader.close();
}

}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}

return strBuffer.toString();
}
/**
* @description 获取输入流
* @param urlStr
* @return
* @throws MalformedURLException
* @throws IOException
*/
public InputStream getIntputStreamFromUrl(String urlStr)
throws MalformedURLException, IOException{

url = new URL(urlStr);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setConnectTimeout(5 * 1000);
httpUrlConn.setReadTimeout(15 * 1000);
httpUrlConn.setDoInput(true);
httpUrlConn.setDoOutput(true);
InputStream inputStream = httpUrlConn.getInputStream();
return inputStream;
}
/**
* @description return value: 1-->文件已存在;
* @description value: 0-->文件下载成功; value: -1-->文件下载失败
* @param urlStr 访问的URL
* @param path   "TZD/"
* @param fileName  "name"
* @return
*/
public int downLoadFiles(String urlStr, String path, String fileName){
InputStream inputStream = null;
try{
DownLoaderSDCardUtils utils = new DownLoaderSDCardUtils();
if(utils.isFileDirectoryExists(path + fileName)){
return 1;
}else{
inputStream = getIntputStreamFromUrl(urlStr);
File resultFile = utils.writeSDCardFromInputStream(path, fileName, inputStream);
if(resultFile==null){
return -1;
}
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return -1;
}finally{
try{
if(inputStream != null){
   inputStream.close();
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
return 0;
}
}

————————————————————————————————————————————————————————————


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值