Android FileInputStream 、 FileOutputStream運用

package com.example.file;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.http.util.EncodingUtils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
private static final String FILE_NAME="file_out.txt";

Button mButton1,mButton2;
EditText mEditText;
TextView mTextView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mButton1=(Button)findViewById(R.id.button1);
        mButton2=(Button)findViewById(R.id.button2);
        mEditText=(EditText)findViewById(R.id.editText1);
        mTextView=(TextView)findViewById(R.id.textView1);
       
       
        mButton2.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub

try {

FileInputStream fileInputStream=openFileInput(FILE_NAME);
byte[] buffer=new byte[1024];

fileInputStream.read(buffer);

String filecontentString=EncodingUtils.getString(buffer, "UTF-8");

 

mTextView.setText(filecontentString);
mTextView.setTextColor(Color.YELLOW);

}
catch (Exception e) {
// TODO: handle exception
}

}
});
       
       
        mButton1.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub

try {
//追加保存

FileOutputStream fileOutputStream=openFileOutput(FILE_NAME, Context.MODE_APPEND);

 

String inputfilecontent=mEditText.getText().toString();

fileOutputStream.write(inputfilecontent.getBytes());
fileOutputStream.close();
}
catch (Exception e) {
// TODO: handle exception
}
}
});
       
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

發佈留言