1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| package com.example.file;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast;
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader;
import static android.os.Environment.MEDIA_MOUNTED;
public class MainActivity extends AppCompatActivity { TextView et, et2;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); et = (TextView) this.findViewById(R.id.et); et2 = (TextView) this.findViewById(R.id.et2); }
public void save(View v) throws Exception { String name = "hello.txt"; String data = et.getText().toString(); FileOutputStream out = openFileOutput(name, Context.MODE_PRIVATE); out.write(data.getBytes()); out.close(); Toast.makeText(this, "数据写入成功", Toast.LENGTH_SHORT).show(); }
public void read(View v) throws IOException { String name = "hello.txt"; FileInputStream input = openFileInput(name); byte[] buffer = new byte[input.available()]; input.read(buffer); String content = new String(buffer); input.close(); Log.e("输出", content); et.setText(content); Toast.makeText(this, "读取成功", Toast.LENGTH_SHORT).show(); }
public void outsave(View v) throws Exception {
String name = "hello.txt"; String data = et2.getText().toString(); String state = Environment.getExternalStorageState(); //判断SD卡是否可用 if (MEDIA_MOUNTED.equals(state)) { File SDPath = Environment.getExternalStorageDirectory(); //获取SD卡路径 File file = new File(SDPath, name); FileOutputStream out = new FileOutputStream(file); out.write(data.getBytes()); out.close(); Toast.makeText(this, "外部数据写入成功", Toast.LENGTH_SHORT).show(); } }
public void outread(View v) throws IOException { String name = "hello.txt"; String state = Environment.getExternalStorageState(); //判断SD卡是否可用 if (MEDIA_MOUNTED.equals(state)) { File SDPath = Environment.getExternalStorageDirectory(); //获取SD卡路径 File file = new File(SDPath, name); FileInputStream input = new FileInputStream(file); BufferedReader br = new BufferedReader(new InputStreamReader(input)); String content = br.readLine(); input.close(); Log.e("输出", content); et2.setText(content); Toast.makeText(this, "外部读取成功", Toast.LENGTH_SHORT).show(); } } }
|