在开发Android应用时有时会用到Input/OutputStream,这两个流的作用分别是读取文件内容,写入文件内容,其中需要注意两点:
1)注意文件的编码格式,一般使用utf-8
2)写入和读取的文件时存储在内存中的,所以对文件的大小有所限制
下面这个例子实现的是:
读取编辑框中输入的内容存储到文件file.txt中,之后读取文件中的内容,实现的截图如下所示:
实现的代码如下所示:
public class OutInputStream_Activity_Test extends Activity { private Button button; private Button button2; private EditText editText; private TextView textView; String string; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_out_input_stream__activity__test); button=(Button)findViewById(R.id.button1); button2=(Button)findViewById(R.id.button2); editText=(EditText)findViewById(R.id.edittext); textView=(TextView)findViewById(R.id.textview); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub OutputStream os = null; try { os = openFileOutput("file.txt", Activity.MODE_PRIVATE); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } string=editText.getText().toString(); try { os.write(string.getBytes("utf-8")); editText.setText(""); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); button2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub try { InputStream is=openFileInput("file.txt"); byte [] buffer=new byte[100]; int byteCount=is.read(buffer); String string=new String(buffer, 0, byteCount, "utf-8"); textView.setText(string); is.close(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }); }}