二、JSON解析
主要是通过JsonWriter类和JsonReader类实现读写功能。
JsonWriter----------具体的写操作如下代码:
writer.beginObject();
writer.name("id").value(product.id);<STRONG>//key-value对应</STRONG>
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操作
和JavaIO操作类似。分为字节流和字符流,推荐用字节流。
写文件:
public void onClick_SaveImageToSDCard(View view)
{
try
{
FileOutputStream fos = new FileOutputStream(
Android.os.Environment.getExternalStorageDirectory()
+ "/image.jpg");<STRONG>//获取sd卡根目录</STRONG>
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);<STRONG>//写文件</STRONG>
}
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);<STRONG>//初始化文件输入流</STRONG>
Bitmap bitmap = BitmapFactory.decodeStream(fis);
imageView.setImageBitmap(bitmap);
fis.close();
}
catch (Exception e)
{
}
}

如果不用数据库的话,以上操作都能实现数据操作,不过更推荐xml文件读写,当然如果在网络应用中,用JSON是最好的轻量级选择。
更多Android相关信息见Android 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=11
