对于一些不变的数据,可以放数据库中,也可以放文本中。这里介绍读取文本中数据。
activity代码:
package com.example.textjson;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import java.io.*;
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getData("person_utf8.txt");
Log.e("convertCodeAndGetText",convertCodeAndGetText("person_utf8.txt"));
}
private void getData(String name) {
InputStream is = null;
byte[] buffer;
try {
is = getAssets().open(name);
buffer = new byte[is.available()];
is.read(buffer);
String json = new String(buffer,"utf-8");
Log.e("json",json);
is.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
}
public String convertCodeAndGetText(String name) {// 转码
String text = "";
BufferedInputStream in = null;
BufferedReader reader = null;
try {
in = new BufferedInputStream(getAssets().open(name));
in.mark(4);
byte[] first3bytes = new byte[3];
in.read(first3bytes);//找到文档的前三个字节并自动判断文档类型。
in.reset();
if (first3bytes[0] == (byte) 0xEF && first3bytes[1] == (byte) 0xBB
&& first3bytes[2] == (byte) 0xBF) {// utf-8
Log.e("charset","utf-8");
reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
} else if (first3bytes[0] == (byte) 0xFF
&& first3bytes[1] == (byte) 0xFE) {
Log.e("charset","unicode");
reader = new BufferedReader(
new InputStreamReader(in, "unicode"));
} else if (first3bytes[0] == (byte) 0xFE
&& first3bytes[1] == (byte) 0xFF) {
Log.e("charset","utf-16be");
reader = new BufferedReader(new InputStreamReader(in,
"utf-16be"));
} else if (first3bytes[0] == (byte) 0xFF
&& first3bytes[1] == (byte) 0xFF) {
Log.e("charset","utf-16le");
reader = new BufferedReader(new InputStreamReader(in,
"utf-16le"));
} else {
Log.e("charset","GBK");
reader = new BufferedReader(new InputStreamReader(in, "GBK"));
}
String str = reader.readLine();
while (str != null) {
text = text + str + "\r\n";
str = reader.readLine();
}
reader.close();
in.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return text;
}
}