Android 第二章 本地文件的读写

 2023-09-15 阅读 26 评论 0

摘要:读写的第一种方式: 使用最初始的IO方式读写到应用包目录下面 package com.example.login;import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.u

 

  1. 读写的第一种方式:
    使用最初始的IO方式读写到应用包目录下面
package com.example.login;import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;public class UserUtils {/*** 保存用户名密码到本地文件中 位置放在app应用包下* @param username* @param passwd* @return*/public static boolean saveUserinfo(String username,String passwd){try {String info =  username +"##"+ passwd;File file = new File("/data/data/com.example.login/info.txt");FileOutputStream outputStream = new FileOutputStream(file);outputStream.write(info.getBytes());outputStream.close();return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 从app应用包路径下读取文件中信息* @return*/public static Map<String,String> readUserinfo(){try {Map map = new HashMap<String,String>();File file = new File("/data/data/com.example.login/info.txt");FileInputStream inputStream = new FileInputStream(file);BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));String info = bufferedReader.readLine();String[] userinfos = info.split("##");map.put("username", userinfos[0]);map.put("passwd", userinfos[1]);return map;} catch (Exception e) {e.printStackTrace();return null;}}
}

2,对版本一进行优化,使用Context上下文环境获取应用包路径进行获取文件路径以及使用新的API在SD卡上操作数据读写
     相关主要API:
     public abstract class Context extends Object
     public abstract File getFilesDir () //获取应用包路径
     public abstract FileOutputStream openFileOutput (String name, int mode) //在应用包中打开一个文件进行准备写入操作,如果文件不存在则进行创建。
     public abstract FileInputStream openFileInput (String name)//在应用包中打开一个文件进行读操作。不能有文件分隔符。
     public class  Environment extends Object
     public static File getExternalStorageDirectory () //获取存储卡目录位置
     public static String getExternalStorageState ()   //获取存储卡状态

package com.example.login;import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;import android.content.Context;
import android.os.Environment;public class UserUtils4Context {/*** 使用上下文环境context API 获取文件目录位置* @param context* @param username* @param passwd* @return*/public static boolean saveUserinfo(Context context,String username,String passwd){try {String info =  username +"##"+ passwd;String path = context.getFilesDir().getPath();File file = new File(path,"info.txt");FileOutputStream outputStream = new FileOutputStream(file);outputStream.write(info.getBytes());outputStream.close();return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 从目录com.example.package/info.txt中读取文件信息* @param context* @return*/public static Map<String,String> readUserinfo(Context context){try {Map map = new HashMap<String,String>();String path = context.getFilesDir().getPath();File file = new File(path,"info.txt");FileInputStream inputStream = new FileInputStream(file);BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));String info = bufferedReader.readLine();String[] userinfos = info.split("##");map.put("username", userinfos[0]);map.put("passwd", userinfos[1]);return map;} catch (Exception e) {e.printStackTrace();return null;}}/*** 优化版 context.openFileOutput 此API会在应用包目录下面创建一个files文件夹 将文件保存在此文件夹中* data/data/com.example.package/files/contextinfo.txt* @param context* @param username* @param passwd* @return*/public static boolean saveUserinfo2(Context context,String username,String passwd){try {String info =  username +"##"+ passwd;FileOutputStream outputStream = context.openFileOutput("contextinfo.txt",0);outputStream.write(info.getBytes());outputStream.close();return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 优化版 从 data/data/com.example.package/files/contextinfo.txt中读取数据* @param context* @return*/public static Map<String,String> readUserinfo2(Context context){try {Map map = new HashMap<String,String>();FileInputStream inputStream = context.openFileInput("contextinfo.txt");BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));String info = bufferedReader.readLine();String[] userinfos = info.split("##");map.put("username", userinfos[0]);map.put("passwd", userinfos[1]);return map;} catch (Exception e) {e.printStackTrace();return null;}}/*** 通过使用 Environment API 将数据保存到sd卡* @param context* @param username* @param passwd* @return*/public static boolean saveUserinfo2sdCard(String username,String passwd){try {String info =  username +"##"+ passwd;String path = Environment.getExternalStorageDirectory().getPath();File file = new File(path,"sdcard.txt");FileOutputStream outputStream = new FileOutputStream(file);outputStream.write(info.getBytes());outputStream.close();return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 通过使用 Environment API 从sd卡上读取数据* @return*/public static Map<String,String> readUserinfoFromSdCard(){try {Map map = new HashMap<String,String>();File file = new File(Environment.getExternalStorageDirectory().getPath(),"sdcard.txt");FileInputStream inputStream = new FileInputStream(file);BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));String info = bufferedReader.readLine();String[] userinfos = info.split("##");map.put("username", userinfos[0]);map.put("passwd", userinfos[1]);return map;} catch (Exception e) {e.printStackTrace();return null;}}
}

3,使用SharedPreferences实现文件的读写
  主要操作步骤,写入:1,获取sp实例 2,获取编辑器;3,添加数据;4,提交数据。
                           读:    1,获取sp实例;2根据key获取value;

package com.example.login;import com.example.loginuseSp.R;import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;public class MainActivity extends Activity {private EditText etUserName;private EditText etUserPasswd;private CheckBox cbIsRem;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);etUserName =  (EditText)findViewById(R.id.et_username);etUserPasswd =  (EditText)findViewById(R.id.et_userpasswd);cbIsRem =  (CheckBox)findViewById(R.id.cb_isrem);//获取实例SharedPreferences sp = getSharedPreferences("config", 0);String name = sp.getString("name","");String passwd = sp.getString("passwd","");Boolean isCk = sp.getBoolean("isCk",false);if(isCk){etUserName.setText(name);etUserPasswd.setText(passwd);cbIsRem.setChecked(true);}}public void loginClick(View v){String userName = etUserName.getText().toString().trim();String passWd = etUserPasswd.getText().toString().trim();if(TextUtils.isEmpty(userName)|| TextUtils.isEmpty(passWd)){Toast.makeText(MainActivity.this, "用户名密码不能为空", 1).show();}else{Toast.makeText(MainActivity.this, "登录成功", 1).show();CheckBox checkBox = (CheckBox)findViewById(R.id.cb_isrem);//获取实例SharedPreferences sp = getSharedPreferences("config", 0);//获取编辑器Editor edit = sp.edit();if(checkBox.isChecked()){boolean result = false;//存储数据edit.putString("name", userName);edit.putString("passwd", passWd);edit.putBoolean("isCk", true);if(result){Toast.makeText(MainActivity.this, "保存成功", 1).show();}else{Toast.makeText(MainActivity.this, "保存失败", 1).show();}}else{edit.putBoolean("isCk", false);}//提交数据edit.commit();}}
}

4,android 实现XML的 读写操作
 

package com.example.createxml;import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Xml;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}/*** 模拟获取数据* @return*/private List<Sms> getList(){ArrayList<Sms> smss = new ArrayList<Sms>(); Sms sms = new Sms("10086","20180903","您的话费余额1209");Sms sms2 = new Sms("95599","20180803","您的银行卡余额1209000");Sms sms3 = new Sms("12306","20170813","您的购票成功");smss.add(sms);smss.add(sms2);smss.add(sms3);return smss;}public void readXML(View v){try {List<Sms> parserXml = parserXml(getAssets().open("fxml.xml"));TextView tv = (TextView)findViewById(R.id.tv_text);tv.setText(parserXml.toString());} catch (IOException e) {e.printStackTrace();}}/*** 创建一个XML文件点击事件* @param v*/public void createXML(View v){XmlSerializer serializer = Xml.newSerializer();File file = new File(Environment.getExternalStorageDirectory().getPath(),"fxml.xml");List<Sms> smsList = getList();try {FileOutputStream fos = new FileOutputStream(file);serializer.setOutput(fos, "utf-8");serializer.startDocument("utf-8", true);serializer.startTag(null, "smss");for (Sms sms : smsList) {serializer.startTag(null, "sms");serializer.attribute(null, "id", sms.getAddress());serializer.startTag(null, "address");serializer.text(sms.getAddress());serializer.endTag(null, "address");serializer.startTag(null, "date");serializer.text(sms.getDate());serializer.endTag(null, "date");serializer.startTag(null, "content");serializer.text(sms.getContent());serializer.endTag(null, "content");serializer.endTag(null, "sms");}serializer.endTag(null,"smss");serializer.endDocument();} catch (Exception e) {e.printStackTrace();}}/*** 解析xml* @param stream* @return*/public List<Sms> parserXml(InputStream stream){XmlPullParser pullParser = Xml.newPullParser();List<Sms> smsList = null;Sms sms = null;try {pullParser.setInput(stream,"utf-8");int eventType = pullParser.getEventType();while (eventType != XmlPullParser.END_DOCUMENT) {switch (eventType) {case XmlPullParser.START_TAG:if("smss".equals(pullParser.getName())){smsList = new ArrayList<Sms>();}else if("sms".equals(pullParser.getName())){sms = new Sms();String id = pullParser.getAttributeValue(null, "id");sms.setId(id);}else if("address".equals(pullParser.getName())){sms.setAddress(pullParser.nextText());}else if("date".equals(pullParser.getName())){sms.setDate(pullParser.nextText());}else if("content".equals(pullParser.getName())){sms.setContent(pullParser.nextText());}break;case XmlPullParser.END_TAG:if("sms".equals(pullParser.getName())){smsList.add(sms);}break;default:break;}eventType = pullParser.next();}} catch (Exception e) {e.printStackTrace();}return smsList;}
}

手机android文件可以删除吗、 

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/57984.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息