本文共 2806 字,大约阅读时间需要 9 分钟。
注意路径我是用的雷电模拟器
layout.xml
<?xml version="1.0" encoding="utf-8"?>public class MainActivity extends AppCompatActivity {
Button savebtn,readbtn,savesbtn,readsbtn; EditText edit; String fileName = “test.txt”; String str; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edit = findViewById(R.id.edit); savebtn = findViewById(R.id.savebtn); savebtn.setOnClickListener(new mClick()); savesbtn = findViewById(R.id.savesbtn); savesbtn.setOnClickListener(new mClick()); readbtn = findViewById(R.id.readbtn); readbtn.setOnClickListener(new mClick()); readsbtn = findViewById(R.id.readsbtn); readsbtn.setOnClickListener(new mClick()); } private class mClick implements View.OnClickListener { @Override public void onClick(View v) { if (vsavebtn){ savefile(); } else if (vreadbtn){ readfile(fileName); } else if (vsavesbtn){ savesSDcar(); } else if (vreadsbtn){ readSDcar(fileName); } } } void readSDcar(String fileName) { if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ File path = Environment.getExternalStorageDirectory(); File sdfile = new File(path,fileName); try { FileInputStream in_file = new FileInputStream(sdfile); byte[] buffer = new byte[1024]; int bytes = in_file.read(buffer); str = new String(buffer,0,bytes); Toast.makeText(MainActivity.this,“文件内容”+str,Toast.LENGTH_LONG).show(); } catch (FileNotFoundException e) { System.out.println(“文件不存在”); // e.printStackTrace(); } catch (IOException e) { System.out.println(“IO流错误”); // e.printStackTrace(); } } } void savesSDcar() { str = edit.getText().toString(); if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)); { File path = Environment.getExternalStorageDirectory(); File sdfile = new File(path,fileName); try { FileOutputStream f_out = new FileOutputStream(sdfile); f_out.write(str.getBytes()); Toast.makeText(MainActivity.this,“文件保存SD”,Toast.LENGTH_LONG).show(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } void readfile(String fileName) { byte[] buffer = new byte[1024]; try { FileInputStream in_file = openFileInput(fileName); int bytes = in_file.read(buffer); str = new String(buffer,0,bytes); Toast.makeText(MainActivity.this,“文件内容”+str,Toast.LENGTH_LONG).show(); } catch (FileNotFoundException e) { System.out.println(“文件不存在”); // e.printStackTrace(); } catch (IOException e) { System.out.println(“IO流错误”); // e.printStackTrace(); } } void savefile() { str = edit.getText().toString(); try { FileOutputStream f_out = openFileOutput(fileName, Context.MODE_PRIVATE); f_out.write(str.getBytes()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }转载地址:http://dkegn.baihongyu.com/