1.assets
assets文件在main文件夹中与java、res同级,assets的文件不会在R资源中生成id,目录中可以有子文件夹,文件不会被编译成二进制,存放到这里的资源在运行打包的时候都会打入程序安装包中。读取方法如下:
try {
InputStream is = getResources().getAssets().open("info.txt");
InputStreamReader isr = new InputStreamReader(is,"UTF-8");
BufferedReader br = new BufferedReader(isr);
// Log.i(TAG,br.readLine());
String in = "";
while ((in = br.readLine()) != null){
// Log.i(TAG,in);
System.out.println(in);
}
} catch (IOException e) {
e.printStackTrace();
}
2.raw
raw文件夹在res目录中,不能有子文件夹,会在R资源中生成id,不会被编译成二进制,这些资源在打包时只打包使用过的资源到安装包中。读取如下:
try {
InputStream is = getResources().openRawResource(R.raw.info);
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
BufferedReader br = new BufferedReader(isr);
String in = "";
while ((in = br.readLine()) != null) {
// Log.i(TAG, in);
System.out.println(in);
}
} catch (IOException e) {
e.printStackTrace();
}
3.android内部储存文件数据
android系统中会在data/data/app包名的文件夹中存储应用数据。例如我们将EditText输入的数据储存在其中:
try {
FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
/**
* Context.MODE_PRIVATE
* 默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,
* 写入的内容会覆盖原文件的内容
*
* Context.MODE_APPEND
* 检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
*
*/
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
osw.write(editText.getText().toString());
osw.flush();
fos.flush();
osw.close();
fos.close();
Toast.makeText(getApplicationContext(), "写入完成", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
读取时:
try {
FileInputStream fis = openFileInput(fileName);
InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
char input[] = new char[fis.available()];
isr.read(input);
isr.close();
fis.close();
String readed = new String(input);
tvShow.setText(readed);
} catch (IOException e) {
e.printStackTrace();
}
4.android外部储存
比较常用的存储方式,同样我们将EditText输入的内容以文件的形式存储的手机中:
File sdCard = Environment.getExternalStorageDirectory();
File myFile = new File(sdCard,"This is my file.txt");
if (sdCard.exists()){
try {
myFile.createNewFile();
// System.out.println(myFile.getAbsolutePath());
Toast.makeText(getApplicationContext(),"文件创建完成",Toast.LENGTH_SHORT).show();
FileOutputStream fos = new FileOutputStream(myFile);
OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8");
osw.write(editText.getText().toString());
osw.flush();
osw.close();
fos.close();
Toast.makeText(getApplicationContext(),"文件写入完成",Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(),"当前系统不具备SD卡目录",Toast.LENGTH_SHORT).show();
}
读取内容:
File myFile = new File(sdCard,"This is my file.txt");
if (myFile.exists()){
try {
FileInputStream fis = new FileInputStream(myFile);
InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
char input[] = new char[fis.available()];
isr.read(input);
isr.close();
fis.close();
String in = new String(input);
tvShow.setText(in);
} catch (IOException e) {
e.printStackTrace();
}
}
----------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------
5.SharedPreferences(题外)
sharedpreferences是一种简单的数据储存方式,将数据以键值对存储在/data/data/包名/shared_prefs下的xml文件中。使用如下:
public class MainActivity extends AppCompatActivity {
private EditText editText;
SharedPreferences preferences;
SharedPreferences.Editor editor;
static final String KEY = "MyValue";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences = getPreferences(Activity.MODE_PRIVATE);
editor = preferences.edit();
editText = (EditText) findViewById(R.id.editText);
findViewById(R.id.btnWrite).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
editor.putString(KEY, editText.getText().toString());
if (editor.commit()) {
Toast.makeText(getApplicationContext(), "写入成功", Toast.LENGTH_SHORT).show();
}
}
});
findViewById(R.id.btnRead).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String in = preferences.getString(KEY, "当前数值不存在");//getString(String key,String defValue) String defValue 如果key对应的值不存在,则传入defValue
Toast.makeText(getApplicationContext(), in, Toast.LENGTH_SHORT).show();
}
});
}
}
sharedpreferences还可以用在应用的首选项上:
importandroid.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.widget.Toast;
public class MyPreferenceActivity extends PreferenceActivity {
// CheckBoxPreference
// ListPreference
// EditTextPreference
PreferenceManager manager;
CheckBoxPreference checkBoxPreference;
ListPreference listPreference;
EditTextPreference editTextPreference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.mypreference);
manager = getPreferenceManager();
checkBoxPreference = (CheckBoxPreference) manager.findPreference("checkbox");
Toast.makeText(getApplicationContext(), "当前的状态为:" + checkBoxPreference.isChecked(), Toast.LENGTH_SHORT).show();
listPreference = (ListPreference) manager.findPreference("list");
Toast.makeText(getApplicationContext(), listPreference.getEntry() + "的开发环境:" + listPreference.getValue(), Toast.LENGTH_SHORT).show();
editTextPreference = (EditTextPreference) manager.findPreference("text");
Toast.makeText(getApplicationContext(), "您输入的内容为:" + editTextPreference.getText(), Toast.LENGTH_SHORT).show();
}
}
R.xml.mypreference是放在res目录中的xml文件夹中的mypreference.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="checkbox"
android:summaryOff="已经关闭"
android:summaryOn="已经开启"
android:title="是否开启" />
<ListPreference
android:entries="@array/entries"
android:entryValues="@array/values"
android:key="list"
android:summary="请点击选择"
android:title="选择一个选项" />
<EditTextPreference
android:dialogMessage="有劳了"
android:dialogTitle="请输入你的名字"
android:key="text"
android:summary="请再次输入"
android:title="请输入" />
</PreferenceScreen>
ListPreference的resources内容如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="entries">
<item>Java</item>
<item>Swift</item>
<item>C#</item>
</string-array>
<string-array name="values">
<item>Eclipse</item>
<item>Xcode</item>
<item>Visual Studio</item>
</string-array>
</resources>
6.xml数据的读写
在assets文件夹中有一份xml文件,如下:
<?xml version="1.0" encoding="utf-8"?>
<Languages cat="it">
<lan id="1">
<name>Java</name>
<ide>Eclipse</ide>
</lan>
<lan id="2">
<name>Swift</name>
<ide>Xcode</ide>
</lan>
<lan id="3">
<name>C#</name>
<ide>Visual Studio</ide>
</lan>
</Languages>
除了各种开源库外,Android 有自己的API来解析xml文件,如下:
TextView textView = (TextView) findViewById(R.id.tv);
//读取xml文件
try {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(getAssets().open("languages.xml"));
Element element = document.getDocumentElement();
NodeList list = element.getElementsByTagName("lan");
for (int i = 0; i < list.getLength(); i++) {
Element lan = (Element) list.item(i);
textView.append(lan.getAttribute("id")+"\n");
textView.append(lan.getElementsByTagName("name").item(0).getTextContent()+"\n");
textView.append(lan.getElementsByTagName("ide").item(0).getTextContent()+"\n");
}
} catch (IOException | ParserConfigurationException | SAXException e) {
e.printStackTrace();
}
//写入xml文件
try {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document documentXML = builder.newDocument();
Element element = documentXML.createElement("country");
element.setAttribute("cat", "it");
//添加里面
//第一个
Element coun1 = documentXML.createElement("coun");
coun1.setAttribute("id", "1");
Element name1 = documentXML.createElement("name");
name1.setTextContent("China");
Element lan1 = documentXML.createElement("language");
lan1.setTextContent("Chinese");
coun1.appendChild(name1);
coun1.appendChild(lan1);
element.appendChild(coun1);
//第二个
Element coun2 = documentXML.createElement("coun");
coun2.setAttribute("id", "2");
Element name2 = documentXML.createElement("name");
name2.setTextContent("America");
Element lan2 = documentXML.createElement("language");
lan2.setTextContent("English");
coun2.appendChild(name2);
coun2.appendChild(lan2);
element.appendChild(coun2);
//
documentXML.appendChild(element);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty("encoding", "UTF-8");
StringWriter sw = new StringWriter();
transformer.transform(new DOMSource(documentXML),new StreamResult(sw));
textView.setText(sw.toString());
} catch (ParserConfigurationException | TransformerException e) {
e.printStackTrace();
}
7.Json数据读取
同样解析assets文件夹下的json文件,需要要Gson之类的解析库,直接利用Android API,JSONObject json = new JSONObject(传入json的Sting内容),具体如下:
json文件:
{
"language":[
{"id":1,"ide":"Eclipse","name":"Java"},
{"id":2,"ide":"Xcode","name":"Swift"},
{"id":3,"ide":"Visual Studio","name":"C#"}
],
"cat":"it"
}
解析:
//读取数据
try {
InputStreamReader isr = new InputStreamReader(getAssets().open("test.json"), "UTF-8");
BufferedReader br = new BufferedReader(isr);
String line;
StringBuilder builder = new StringBuilder();
while ((line = br.readLine()) != null) {
builder.append(line);
}
br.close();
isr.close();
JSONObject root = new JSONObject(builder.toString());
System.out.println("cat = " + root.getString("cat"));
JSONArray array = root.getJSONArray("language");
for (int i=0;i<array.length();i++){
JSONObject lan = array.getJSONObject(i);
System.out.println("---------------------------------");
System.out.println("id = " + lan.getInt("id"));
System.out.println("ide = " + lan.getString("ide"));
System.out.println("name = " + lan.getString("name"));
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
//写入数据
try {
JSONObject root = new JSONObject();
root.put("cat","it");
//创建单个对象 {"id":1,"ide":"Eclipse","name":"Java"}
JSONObject lan1 = new JSONObject();
lan1.put("id",1);
lan1.put("ide","Eclipse");
lan1.put("name","Java");
//{"id":2,"ide":"Xcode","name":"Swift"}
JSONObject lan2 = new JSONObject();
lan2.put("id",2);
lan2.put("ide","Xcode");
lan2.put("name","Swift");
//{"id":3,"ide":"Visual Studio","name":"C#"}
JSONObject lan3 = new JSONObject();
lan3.put("id",3);
lan3.put("ide","Visual Studio");
lan3.put("name","C#");
//JSON数据添加单个对象
JSONArray array = new JSONArray();
array.put(lan1);
array.put(lan2);
array.put(lan3);
root.put("langusges",array);
System.out.println(root.toString());
} catch (JSONException e) {
e.printStackTrace();
}