安卓初学者之一个简单的记事本

来源:互联网 发布:办公软件培训视频 编辑:程序博客网 时间:2024/04/28 18:32

一个非常简单的小应用,整个代码还不到一百行,之前都是跟着教程做,看一眼视频写几行代码。这还是第一次独立完成一个项目,自己查API,遇到问题自己查,虽然代码量非常少,但感觉收获不少。代码如下。

package com.example.note;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends Activity {
EditText edt_note;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt_note = (EditText) findViewById(R.id.edt_note);
}
public void onClick(View view){‘
switch (view.getId()) {
case R.id.btn_exit://结束该应用
Log.v("long", "btn_exit");
finish();
System.exit(0);
break;
case R.id.btn_save://保存EditText控件中的内容
Log.v("long", "btn_save");
write();
break; 
case R.id.btn_open://打开上次保存的txt文件
Log.v("long", "btn_open");
String text = read();
edt_note.setText(text);//设置EditText中显示的内容为从文件中读取的字符串
edt_note.setSelection(text.length());//将光标设置在文本的最后一格
break;
default:
break;
}
}

//此方法读取本地SD卡中固定路径的txt文件
private String read(){
FileInputStream input = null;
String string;
String path = Environment.getExternalStorageDirectory().toString() + "/New Folder/long.txt";//设置读取文件路径
byte[] buffer = new byte[2048];//用作缓存的byte数组
try{
input = new FileInputStream(path);//定义输入流
int len = input.read(buffer);//读取输入流,长度为buffer数组长度,并返回有效字节总长度
string = new String(buffer, 0, len);//使用此数组生成一个字符串
return string;//将此字符串作为返回值
}catch(IOException e){
e.printStackTrace();
}
finally{ //方法结束前关闭输入流,释放系统资源
if(input != null)
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}


//此方法将EditText控件中的文本保存到本地txt文件
private void write(){
FileOutputStream output = null;
String string = edt_note.getText().toString();//获取当前文本框中的文本内容并转换为字符串
byte[] buffer = string.getBytes();//将字符串使用默认编码方式编码为byte序列并存入数组中
String path = Environment.getExternalStorageDirectory().toString() + "/New Folder/long.txt";//设定生产文件路径
try {
output = new FileOutputStream(path);//定义一个输出流
output.write(buffer);//数组中的内容写入
} catch (IOException e) {
e.printStackTrace();
}
finally{ //方法结束前关闭输出流,释放系统资源
if(output != null)
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

xml文件也非常简单,就是三个button下面一个EditText,这里就不贴出来了。

0 0
原创粉丝点击