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();
}
}
}