JSON XML IO数据操作
一、XML解析
package org.hjw.service; import java.util.ArrayList;
import java.util.List; import org.hjw.model.Product;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler; public class XML2Product extends DefaultHandler {
private Product product;
private List<Product> products;
StringBuffer buffer = new StringBuffer(); public List<Product> getProducts() {
return products;
} @Override
public void characters(char[] ch, int start, int length)
throws SAXException {
buffer.append(ch, start, length);
super.characters(ch, start, length);
} @Override
public void startDocument() throws SAXException {
products = new ArrayList<Product>();
} @Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (localName.equals("product")) {
product = new Product();
}
super.startElement(uri, localName, qName, attributes);
} @Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (localName.equals("product")) {
products.add(product);
} else if (localName.equals("id")) {
product.setId(Integer.parseInt(buffer.toString().trim()));
buffer.setLength(0);
} else if (localName.equals("name")) {
product.setName(buffer.toString().trim());
buffer.setLength(0);
} else if (localName.equals("price")) {
product.setPrice(Float.parseFloat(buffer.toString().trim()));
buffer.setLength(0);
}
super.endElement(uri, localName, qName);
} }
然后只需在主函数中:
InputStream is = getResources().openRawResource(R.raw.products);
XML2Product xml2Product = new XML2Product();
android.util.Xml.parse(is, Xml.Encoding.UTF_8, xml2Product);
List<Product> products = xml2Product.getProducts();
二、JSON解析
主要是通过JsonWriter类和JsonReader类实现读写功能。
writer.beginObject();
writer.name("id").value(product.id);//key-value对应
writer.name("name").value(product.name);
writer.endObject();
一般来说,我们要尽可能的分层次的解析,让代码实现更好的分离,流操作-数组操作-对象操作。
JsonReader--------具体的读操作:
reader.beginObject();
while (reader.hasNext())
{
String field = reader.nextName();//游标往后移 if (field.equals("id"))
{
id = reader.nextString();//获取数据
}
else if (field.equals("name"))
{
name = reader.nextString(); }
else
{
reader.skipValue();
}
}
reader.endObject();
一般来说,只要Reader初始化输入流,通过ArrayList接收,分层次的读取便可实现功能。
三、IO操作
public void onClick_SaveImageToSDCard(View view)
{
try
{
FileOutputStream fos = new FileOutputStream(
android.os.Environment.getExternalStorageDirectory()
+ "/image.jpg");//获取sd卡根目录
InputStream is = getResources().getAssets().open("image.jpg"); byte[] buffer = new byte[8192];
int count = 0;
while ((count = is.read(buffer)) >= 0)
{
fos.write(buffer, 0, count);//写文件
}
fos.close();
is.close();
Toast.makeText(this, "已成功将图像文件写到SD卡上.", Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
读文件:
public void onClick_ReadImageFromSDCard(View view)
{
String filename = android.os.Environment.getExternalStorageDirectory()
+ "/image.jpg"; if (!new File(filename).exists())
{
Toast.makeText(this, "还没有往SD卡写入图像文件", Toast.LENGTH_LONG).show();
return;
}
ImageView imageView = (ImageView) findViewById(R.id.imageview);
try
{
FileInputStream fis = new FileInputStream(filename);//初始化文件输入流
Bitmap bitmap = BitmapFactory.decodeStream(fis);
imageView.setImageBitmap(bitmap); fis.close();
}
catch (Exception e)
{ }
}
如果不用数据库的话,以上操作都能实现数据操作,不过更推荐xml文件读写,当然如果在网络应用中,用JSON是最好的轻量级选择。
JSON XML IO数据操作的更多相关文章
- XML文件数据操作
#region XML序列化文件和反序列化 /// <summary> /// 通用类的保存函数,可以将已经声明过可序列化的类以文件方式保存起来. /// 保存格式分为 XML明文式和 二 ...
- ASP.NET MVC WebApi 返回数据类型序列化控制(json,xml) 用javascript在客户端删除某一个cookie键值对 input点击链接另一个页面,各种操作。 C# 往线程里传参数的方法总结 TCP/IP 协议 用C#+Selenium+ChromeDriver 生成我的咕咚跑步路线地图 (转)值得学习百度开源70+项目
ASP.NET MVC WebApi 返回数据类型序列化控制(json,xml) 我们都知道在使用WebApi的时候Controller会自动将Action的返回值自动进行各种序列化处理(序列化为 ...
- json和xml封装数据、数据缓存到文件中
一.APP的通信格式之xml xml:扩展标记语言,可以用来标记数据,定义数据类型,是一种允许用户对自己标记语言进行定义的源语言.XML格式统一,扩平台语言,非常适合数据传输和通信,业界公认的标准. ...
- HttpClient获取返回类型为JSON或XML的数据
Java_HttpClient获取返回类型为JSON或XML的数据 原创 2017年04月06日 17:38:29 706 HttpClient 获取返回类型为JSON或XML的数据 使用httpco ...
- IO流总结---- 字节流 ,字符流, 序列化 ,数据操作流,打印流 , Properties 集合
笔记内容: 什么是流 字节流 字符流 序列化 数据操作流(操作基本数据类型的流)DataInputStream 打印流 Properties 集合 什么是流: 流是个抽象的概念,是对输入输出设备的抽象 ...
- python 发送json数据操作实例分析 - python
文章来源:嗨学网 敏而好学论坛www.piaodoo.com 欢迎大家相互学习 本文实例讲述了python 发送json数据操作.分享给大家供大家参考,具体如下: # !/usr/bin/env py ...
- Python常用的数据文件存储的4种格式(txt/json/csv/excel)及操作Excel相关的第三方库(xlrd/xlwt/pandas/openpyxl)(2021最新版)
序言:保存数据的方式各种各样,最简单的方式是直接保存为文本文件,如TXT.JSON.CSV等,除此之外Excel也是现在比较流行的存储格式,通过这篇文章你也将掌握通过一些第三方库(xlrd/xlwt/ ...
- (Unity)XML文件读写与IO文件操作类使用介绍
using System.Xml; //xml文件操作命名空间 #region 写入操作 void WriteXMLFile(string _fileName) { Xm ...
- php返回json,xml,JSONP等格式的数据
php返回json,xml,JSONP等格式的数据 返回json数据: header('Content-Type:application/json; charset=utf-8'); $arr = a ...
随机推荐
- Matlab中的取整-floor,ceil,fix,round
FLOOR Round towards minus infinity. FLOOR(X) rounds the elements of X to the nearest integers toward ...
- 使用wininet向FTP服务器发送文件
.h #pragma once #include <windows.h> #include <tchar.h> #include <string> #include ...
- BZOJ 1257 余数之和sum(分块优化)
题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=46954 题意:f(n, k)=k mod 1 + k mod 2 ...
- BZOJ 4010: [HNOI2015]菜肴制作( 贪心 )
把图反向,然后按拓扑序贪心地从大到小选, 最后输出.set比priority_queue慢... --------------------------------------------------- ...
- CSS3 模拟笑脸
参考 http://www.html5tricks.com/demo/html5-css3-smile-face/index.html 它还做了舌头... 一开始我都是用JS实现的动画 当然了 眼 ...
- HDU2577:How to Type(DP)
Problem Description Pirates have finished developing the typing software. He called Cathy to test hi ...
- C++模板:欧拉函数
单个欧拉函数 int eular(int n){ int ret=1,i; for(i=2;i*i<=n;i++) if(n%i==0){ n/=i,ret*=i-1; while(n%i==0 ...
- Network of Schools(强连通分量+缩点) (问添加几个点最少点是所有点连接+添加最少边使图强连通)
Network of Schools Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 13801 Accepted: 55 ...
- 把Web Form项目转换成MVC项目
http://umbraco.com/follow-us/blog-archive/2013/7/14/moving-from-webforms-to-mvc.aspx https://codinga ...
- 数据库SQL基础知识
数据库: 结构化查询语言(Structured Query Language)简称SQL: 数据库管理系统(Database Management System)简称DBMS: 数据库管理 ...