界面一个EditText,一个Button,其他随意。
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.example.bz0209.myapplication.model.FileService;
public class MainActivity extends AppCompatActivity {
private EditText edit;
private FileService fs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fs = new FileService(this);
edit = (EditText)findViewById(R.id.editText);
edit.setText(fs.Read());
}
public void OnSave(View view){
fs.Save(edit.getText().toString());
Toast.makeText(this,"ok", Toast.LENGTH_LONG).show();
}
}
关键是这个class,因为android的文件读写方式和java貌似还是不一样……
(敲桌子,划重点~)那两层包装,只为了不用隐式转换而用那个能直接得到相同类型的方法。
import android.content.Context;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
/**
* Created by Administrator on 2017/4/10.
*/
public class FileService {
private Context context;
public FileService(Context context){
this.context = context;
}
public boolean Save(String content){
FileOutputStream fos = null;
OutputStreamWriter osw = null;
BufferedWriter bw = null;
try {
/*1:文件名,2:操作模式*/
fos = context.openFileOutput("data.txt", Context.MODE_PRIVATE);//得到文件输出流
osw = new OutputStreamWriter(fos);
bw = new BufferedWriter(osw);//包装
bw.write(content);
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try{
if(bw != null)
bw.close();
if (osw != null)
osw.close();
if(bw != null)
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
public String Read(){
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader wr = null;
String content = null;
try {
fis = context.openFileInput("data.txt");
isr = new InputStreamReader(fis);
wr = new BufferedReader(isr);
content = wr.readLine();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if(wr != null)
wr.close();
if(isr != null)
isr.close();
if(fis != null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return content;
}
}
打开能显示之前保存的string,点击按钮能保存当前的string