import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
public class MainActivity extends Activity
{
Button btn_write,btn_read;
CheckBox check;
TextView text_show,file_show;
EditText edit;
public final String filename = "file_test.txt";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_write = (Button)findViewById(R.id.button_write);
btn_read = (Button)findViewById(R.id.button_read);
check = (CheckBox)findViewById(R.id.checkBox1);
text_show = (TextView)findViewById(R.id.showview1);
file_show = (TextView)findViewById(R.id.showfile);
edit = (EditText)findViewById(R.id.edit1);
edit.selectAll();
edit.findFocus();
Button.OnClickListener btnListener = new Button.OnClickListener(){
@Override
public void onClick(View v)
{
// TODO 自动生成的方法存根
switch(v.getId())
{
case R.id.button_read:
text_show.setText("");
FileInputStream fis = null;
try
{
fis = openFileInput(filename);
if(fis.available() == 0)
{
return;
}
byte[] readBytes = new byte[fis.available()];
while(fis.read(readBytes) != -1){
}
String text = new String(readBytes);
file_show.setText(text);
text_show.setText("文件读取信息为:"+text.length());
} catch (FileNotFoundException e1)
{
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
return;
case R.id.button_write:
FileOutputStream fos = null;
try{
if(check.isChecked())
{
fos = openFileOutput(filename,Context.MODE_APPEND);
}
else {
fos = openFileOutput(filename,Context.MODE_PRIVATE);
}
String text = edit.getText().toString() + "\n";
fos.write(text.getBytes());
text_show.setText(""+text.length());
edit.setText("");
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e)
{
// TODO 自动生成的 catch 块
e.printStackTrace();
}
finally{
if (fos != null){
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return;
}
}
};
btn_write.setOnClickListener(btnListener);
btn_read.setOnClickListener(btnListener);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
}