-
The first way to read and write:
Use the initial IO mode to read and write to the application package directory
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 { /** * Save the user name and password to the local file and place it under the app package * @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; } } /** * Read the information in the file from the app package path * @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. Optimize version 1, use Context context environment to get application package path to get file path, and use new API to read and write data on SD card
Relevant main API:
public abstract class Context extends Object
public abstract File getFilesDir() / / get the application package path
public abstract FileOutputStream openFileOutput (String name, int mode) / / open a file in the application package to prepare for writing. If the file does not exist, create it.
public abstract FileInputStream openFileInput (String name) / / open a file in the application package for reading. Cannot have a file separator.
public class Environment extends Object
public static File getExternalStorageDirectory() / / get the storage card directory location
public static String getExternalStorageState() / / get the status of the memory card
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 { /** * Get the file directory location using 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; } } /** * Read file information from the directory 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; } } /** * Optimized version of context.openFileOutput this API will create a files folder under the application package directory to save the files in this folder * 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; } } /** * The optimized version reads data from 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; } } /** * Save data to sd card by using Environment API * @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; } } /** * Read data from sd card by using Environment API * @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. Use SharedPreferences to read and write files
The main operation steps are as follows: 1. Get sp instance 2. Get editor; 3. Add data; 4. Submit data.
Read: 1, get sp instance; 2, get value according to key;
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; @Override protected 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); //Get examples 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, "User name and password cannot be empty", 1).show(); }else{ Toast.makeText(MainActivity.this, "Login successfully", 1).show(); CheckBox checkBox = (CheckBox)findViewById(R.id.cb_isrem); //Get examples SharedPreferences sp = getSharedPreferences("config", 0); //Get editor Editor edit = sp.edit(); if(checkBox.isChecked()){ boolean result = false; //Store data edit.putString("name", userName); edit.putString("passwd", passWd); edit.putBoolean("isCk", true); if(result){ Toast.makeText(MainActivity.this, "Save successfully", 1).show(); }else{ Toast.makeText(MainActivity.this, "Save failed", 1).show(); } }else{ edit.putBoolean("isCk", false); } //Submit data edit.commit(); } } }
4. Android implements the read and write operation of 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 { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } /** * Analog data acquisition * @return */ private List<Sms> getList(){ ArrayList<Sms> smss = new ArrayList<Sms>(); Sms sms = new Sms("10086","20180903","Your phone balance 1209"); Sms sms2 = new Sms("95599","20180803","Your bank card balance is 1209000"); Sms sms3 = new Sms("12306","20170813","Your ticket was purchased successfully"); 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(); } } /** * Create an XML file click event * @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(); } } /** * Parsing 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; } }