package com.Android.ReadAndWrite;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
Button BtnWrite,BtnRead;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//写文件
BtnWrite=(Button)findViewById(R.id.BtnWrite);
BtnWrite.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
BtnRead.setEnabled(true);
try
{
WriteFile("这是我使用Java的IO库写入的一个文本文件,文本内容是:野草,根本不深,花叶不美,然而吸取露,吸取水,吸取陈死人的血和肉,各各夺取它的生存。当生存时,还是将遭践踏,将遭删刈,直至于死亡而朽腐。但我坦然、欣然。我将大笑,我将歌唱。我自爱我的野草,但我憎恶这以野草作装饰的地面。地火在地下运行,奔突,熔岩一旦喷出,将烧尽一切野草,以及乔木,于是并且无可朽腐。但我坦然、欣然。我将大笑,我将歌唱。天地有如此静穆,我不能大笑而且歌唱。天地即不如此静穆,我或者也将不能。我以这一丛野草,在明与暗,生与死,过去与未来之际,献于友与仇,人与兽,爱者与不爱者之前特证。");
}
catch (IOException e)
{
e.printStackTrace();
}
}
});
//读文件
BtnRead=(Button)findViewById(R.id.BtnRead);
BtnRead.setEnabled(false);
BtnRead.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
try
{
tv.setText(ReadFile());
}
catch (IOException e)
{
e.printStackTrace();
}
}
});
tv=(TextView)findViewById(R.id.TextView);
}
private void WriteFile(String Content) throws IOException
{
try
{
FileOutputStream fos=openFileOutput("KeyNote.txt",MODE_APPEND);
fos.write(Content.getBytes());
fos.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
private String ReadFile() throws IOException
{
try
{
FileInputStream fis=openFileInput("KeyNote.txt");
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
return new String(buffer);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
return null;
}
@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;
}
}
阅读(1383) | 评论(0) | 转发(0) |