一.Android文件读写操作
1. 文件的基本操作。
2.读取Assets与raw文件夹中的数据。
3. 读写内部存储与外部存储。
<strong> String fileName="t.txt";
//1.文件基本操作
File file=new File(Environment.getExternalStorageDirectory(),fileName);
if (!file.exists()) {
try {
file.createNewFile();
LogUtils.e("文件创建成功" + file.getAbsolutePath());
FileOutputStream outputStream=new FileOutputStream(file);
OutputStreamWriter outputStreamWriter=new OutputStreamWriter(outputStream);
outputStreamWriter.write("gst is ok");
outputStreamWriter.flush();
outputStreamWriter.close();
outputStream.close();
LogUtils.e("文件写入成功" + file.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}else{
LogUtils.e("文件创建失败");
}
//2.读取Assets中的文件
try {
InputStream inputStream=getResources().getAssets().open("t.txt");
MediaPlayer mediaPlayer=new MediaPlayer();
mediaPlayer.setDataSource(getResources().getAssets().openFd("shot.mp3").getFileDescriptor());
int length=inputStream.available();
byte[] bytes=new byte[length];
inputStream.read(bytes,0,length);
String msg=new String(bytes);
LogUtils.e(msg);
} catch (IOException e) {
e.printStackTrace();
}
//3.读取raw下的文件
try {
InputStream inputStream=getResources().openRawResource(R.raw.t);
int length=inputStream.available();
byte[] bytes=new byte[length];
inputStream.read(bytes,0,length);
String msg=new String(bytes);
LogUtils.e(msg);
} catch (IOException e) {
e.printStackTrace();
}
//4.读取外部存储
if (file.exists()) {
try {
FileInputStream inputStream=new FileInputStream(file);
byte[] bytes=new byte[1024];
int count=0;
StringBuffer buffer=new StringBuffer();
while ((count=inputStream.read(bytes))!=-1){
buffer.append(new String(bytes,0,count));
}
LogUtils.e("文件读取成功" + buffer);
} catch (IOException e) {
e.printStackTrace();
}
}else{
LogUtils.e("文件不存在");
}
</strong>
二.Android读写首选项
SharedPreference是Android系统中轻量级存储数据的一种方式,操作简便快捷,它的本质是基于XML文件存储Key-Value键值对数据,适合存放程序状态的配置信息。
1. SharedPreference的概念与使用
2. PreferenceActivity的操作
<strong><PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<SwitchPreference
android:key="example_switch"
android:title="@string/pref_title_social_recommendations"
android:summary="@string/pref_description_social_recommendations"
android:defaultValue="true" />
<!-- NOTE: EditTextPreference accepts EditText attributes. -->
<!-- NOTE: EditTextPreference's summary should be set to its value by the activity code. -->
<EditTextPreference
android:key="example_text"
android:title="@string/pref_title_display_name"
android:defaultValue="@string/pref_default_display_name"
android:selectAllOnFocus="true"
android:inputType="textCapWords"
android:capitalize="words"
android:singleLine="true"
android:maxLines="1" />
<!-- NOTE: Hide buttons to simplify the UI. Users can touch outside the dialog to
dismiss it. -->
<!-- NOTE: ListPreference's summary should be set to its value by the activity code. -->
<ListPreference
android:key="example_list"
android:title="@string/pref_title_add_friends_to_messages"
android:defaultValue="-1"
android:entries="@array/pref_example_list_titles"
android:entryValues="@array/pref_example_list_values"
android:negativeButtonText="@null"
android:positiveButtonText="@null" />
<CheckBoxPreference
android:title="是否开启"
android:summaryOn="已经开启"
android:summaryOff=""
android:key="checkbox">
</CheckBoxPreference>
</PreferenceScreen>
</strong>
三.使用SQLite数据库存储数据
1.使用代码读写SQLite数据库
2.通过界面操作数据库
四.应用间数据传递
1.认识ContentProvider。
2.使用SQLite存储简单的数据和应用间通过ContentProvider通信数据。
五.在Android中操作XML数据
03:44
1.XML数据结构知识。
XML,即可扩展标记语言(Extensible Markup Language),标准通用标记语言的子集,一种用于标记电子文件使其具有结构性的标记语言。它可以用来标记数据、定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言。本课时对XML数据格式进行介绍。
2.在Android中读取XML中的数据。 public void readXml(View view) {
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
DocumentBuilder builder= null;
StringBuffer buffer=new StringBuffer();
try {
builder = factory.newDocumentBuilder();
Document document=builder.parse(getAssets().open("languages.xml"));
Element element=document.getDocumentElement();
NodeList nodeList=element.getElementsByTagName("lan");
for (int i = 0; i < nodeList.getLength(); i++) {
Element element1= (Element) nodeList.item(i);
buffer.append(element1.getAttribute("id")+"\n");
buffer.append(element1.getElementsByTagName("name").item(0).getTextContent()+"\n");
buffer.append(element1.getElementsByTagName("ide").item(0).getTextContent()+"\n");
}
LogUtils.e(buffer.toString());
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
3.在Android中生成XML数据。
public void writeXml(View view) {
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder=factory.newDocumentBuilder();
Document newXml=builder.newDocument();
Element languages=newXml.createElement("languages");
languages.setAttribute("cat", "it");
Element lan1=newXml.createElement("lan");
lan1.setAttribute("id", "1");
Element name1=newXml.createElement("name");
name1.setTextContent("Java");
Element ide1=newXml.createElement("ide");
ide1.setTextContent("Eclipse");
lan1.appendChild(name1);
lan1.appendChild(ide1);
languages.appendChild(lan1);
Element lan2=newXml.createElement("lan");
lan2.setAttribute("id", "2");
Element name2=newXml.createElement("name");
name2.setTextContent("Swift");
Element ide2=newXml.createElement("ide");
ide2.setTextContent("XCode");
lan2.appendChild(name2);
lan2.appendChild(ide2);
languages.appendChild(lan2);
Element lan3=newXml.createElement("lan");
lan3.setAttribute("id", "3");
Element name3=newXml.createElement("name");
name3.setTextContent("C++");
Element ide3=newXml.createElement("ide");
ide3.setTextContent("Visual Studio");
lan3.appendChild(name3);
lan3.appendChild(ide3);
languages.appendChild(lan3);
newXml.appendChild(languages);
TransformerFactory transformerFactory=TransformerFactory.newInstance();
Transformer transformer=transformerFactory.newTransformer();
transformer.setOutputProperty("encoding","utf-8");
transformer.setOutputProperty("version","1.0");
File file=new File(Environment.getExternalStorageDirectory()+File.separator+"languages.xml");
if (!file.exists()){
file.createNewFile();
}
FileOutputStream outputStream=new FileOutputStream(file);
transformer.transform(new DOMSource(newXml),new StreamResult(outputStream));
LogUtils.i("transformer succeed");
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
}
六.在Android中操作JSON数据
1.JSON数据的特点与优势。
JSON:JavaScript 对象表示法(JavaScript Object Notation)。独立于语言和平台,比 XML 更小、更快,更易解析。如今JSON数据已经成为了互联网中大多数数据的传递方式,所以必须要熟练掌握。
2.在Android中加载并解析JSON数据。
public void readJson(View view){
try {
InputStream inputStream=getAssets().open("test.json");
byte[] bytes=new byte[1024];
int count=0;
StringBuffer buffer=new StringBuffer();
while ((count=inputStream.read(bytes))>0){
buffer.append(new String(bytes,0,count));
}
JSONObject root=new JSONObject(buffer.toString());
LogUtils.i("cat="+root.getString("cat"));
JSONArray jsonArray=root.getJSONArray("people");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject=jsonArray.getJSONObject(i);
LogUtils.i("firstName="+jsonObject.getString("firstName"));
LogUtils.i("lastName="+jsonObject.getString("lastName"));
LogUtils.i("email="+jsonObject.getString("email"));
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
3.在Android中生成JSON数据。
public void writeJson(View view){
try {
JSONObject root=new JSONObject();
root.put("cat","it");
JSONObject people1=new JSONObject();
people1.put("firstName","Brett");
people1.put("lastName","McLaughlin");
people1.put("email","aaaa");
JSONObject people2=new JSONObject();
people2.put("firstName","Brett");
people2.put("lastName","McLaughlin");
people2.put("email","aaaa");
JSONObject people3=new JSONObject();
people3.put("firstName","Brett");
people3.put("lastName","McLaughlin");
people3.put("email","aaaa");
JSONArray jsonArray=new JSONArray();
jsonArray.put(people1);
jsonArray.put(people2);
jsonArray.put(people3);
root.put("people",jsonArray);
File file=new File(Environment.getExternalStorageDirectory()+File.separator+"test.json");
if (!file.exists()){
file.createNewFile();
}
FileOutputStream outputStream=new FileOutputStream(file);
outputStream.write(root.toString().getBytes());
LogUtils.i(root.toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}