Android File文件的读写操作,本程序实现两个文本框和两个按钮,其中一个文本框和一个按钮用于读取文件内容、另一个文本框和另一个按钮用于写入。
java代码:
package com.example.activity;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class FileReadWrite extends Activity implements OnClickListener {
private static final String FILE_NAME = "/zhuhuajie.bin";
private EditText readtext;
private EditText writetext;
private Button read;
private Button write;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.filereadwrite);
init();
read.setOnClickListener(this);
write.setOnClickListener(this);
}
public void init(){
readtext=(EditText)findViewById(R.id.readtext);
writetext=(EditText)findViewById(R.id.writetext);
read=(Button)findViewById(R.id.read);
write=(Button)findViewById(R.id.write);
}
@Override
public void onClick(View v)
{
switch(v.getId())
{
case R.id.read:
readtext.setText(read());
break;
case R.id.write:
write(writetext.getText().toString());
writetext.setText("");
break;
}
}
private String read(){
try {
//如果手机插入了SD卡,而且应用程序具有访问SD的权限
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
//获取SD卡对应的存储目录
File sdCardDir=Environment.getExternalStorageDirectory();
//获取指定文件对应的输入流
FileInputStream fis=new FileInputStream(sdCardDir.getCanonicalPath()+FILE_NAME);
//将指定输入流包装成BufferedReader
BufferedReader br=new BufferedReader(new InputStreamReader(fis));
StringBuilder sb=new StringBuilder("");
String line=null;
while((line=br.readLine())!=null)
{
sb.append(line);
}
return sb.toString();
}
}catch (Exception e)
{
e.printStackTrace();
}
return null;
}
private void write(String content)
{
try
{
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
File sdCardDir=Environment.getExternalStorageDirectory();
File targetFile=new File(sdCardDir.getCanonicalPath()+FILE_NAME);
//以指定文件创建RandomAccessFile对象
RandomAccessFile raf=new RandomAccessFile(targetFile,"rw");
//将文件记录指针移动到最后
raf.seek(targetFile.length());
//输出文件内容
raf.write(content.getBytes());
raf.close();
}
}catch(Exception e)
{
e.printStackTrace();
}
}
}