android-读取和保存文件实例

敲多了就会了,哈哈哈!一起加油!

注意路径我是用的雷电模拟器

layout.xml


main.java

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 (v
readbtn){
readfile(fileName);
}
else if (vsavesbtn){
savesSDcar();
}
else if (v
readsbtn){
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();
}
}
}

你可能感兴趣的:(Android-菜鸟记录篇)