1 package com.hanqi.testapp3;
2
3 import android.content.SharedPreferences;
4 import android.os.Bundle;
5 import android.support.v7.app.AppCompatActivity;
6 import android.view.View;
7 import android.widget.EditText;
8 import android.widget.TextView;
9 import android.widget.Toast;
10
11 import java.io.File;
12 import java.io.FileInputStream;
13 import java.io.FileOutputStream;
14 import java.io.PrintStream;
15
16 public class MainActivity extends AppCompatActivity {
17
18 EditText et_1;
19 TextView tv_1;
20
21 @Override
22 protected void onCreate(Bundle savedInstanceState) {
23 super.onCreate(savedInstanceState);
24 setContentView(R.layout.activity_main);
25
26 et_1 = (EditText)findViewById(R.id.et_1);
27 tv_1 = (TextView)findViewById(R.id.tv_1);
28
29 }
30
31 //写内部文件
32 public void bt2_OnClick(View v)
33 {
34 //从内存里写入文件
35
36 //1、得到内部的存储目录
37 try {
38
39 File file = getFilesDir();
40
41 String path = file.getAbsolutePath();
42
43 Toast.makeText(MainActivity.this, "path = " + path, Toast.LENGTH_SHORT).show();
44
45 //2、用输出流写入文件
46 FileOutputStream fos = openFileOutput("text.txt",MODE_APPEND);
47
48 //3、写入文件内容
49 PrintStream ps = new PrintStream(fos);
50
51 String str = et_1.getText().toString();
52
53 ps.println(str);
54 //ps.println("自动换行");
55 ps.close();
56 fos.close();
57
58 Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
59 }
60 catch (Exception e)
61 {
62 Toast.makeText(MainActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
63 }
64
65 }
66
67
68 //读
69 public void bt3_OnClick (View v)
70 {
71 try {
72 //输入流
73 FileInputStream fis = openFileInput("text.txt");
74
75 //1、定义byte[]
76 byte[] b = new byte[1024];
77 int i = 0; //读到的数据长度
78
79 String str1 = "";
80
81 //2、循环读
82 while ((i = fis.read(b)) > 0)
83 {
84 String str = new String(b, 0, i);
85
86 str1 += str;
87 }
88
89 fis.close();
90
91 tv_1.setText(str1);
92 }
93 catch (Exception ex)
94 {
95
96 }
97 }
98
99 }