创建一个工程LearnReadWriteInternalData,空Activity 及一个按钮, |
先直接运行到手机或虚拟机中,此时就会在手机系统的固定地方创建一个文件夹 Android系统的Data文件夹\内部的Data\找到我们的工程
|
在Andriod Studio的工具栏中选择DDMS(AndroidDevice Monitor) |
|
<EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/et" android:hint="在这里输入内容" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="保存数据" android:id="@+id/btnWrite" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="读取数据" android:id="@+id/btnRead" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="New Text" android:id="@+id/tvShow" />
|
public class MainActivity extends AppCompatActivity implements View.OnClickListener { private TextView show; private EditText et; private String fileName="test"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); show= (TextView) findViewById(R.id.tvShow); et= (EditText) findViewById(R.id.et); findViewById(R.id.btnRead).setOnClickListener(this); findViewById(R.id.btnWrite).setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.btnRead: try { FileInputStream fis= openFileInput(fileName); InputStreamReader is=new InputStreamReader(fis,"UTF-8"); char input[]=new char[fis.available()]; is.read(input); is.close(); fis.close(); String readed=new String(input); show.setText(readed); System.out.println("读取数据成功"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } break; case R.id.btnWrite: try { FileOutputStream fos=openFileOutput(fileName, Context.MODE_PRIVATE); //应用程序输入写入内部存储 OutputStreamWriter osw=new OutputStreamWriter(fos,"UTF-8"); osw.write(et.getText().toString()); osw.flush(); fos.flush(); osw.close(); fos.close(); Toast.makeText(MainActivity.this, "写入内部数据完成", Toast.LENGTH_LONG); System.out.println("写入内部数据完成"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } break; } } }
|