android文件读写
文件读写时,会在工程下面的files文件夹里面生成文件名为(你个人起的).格式的文件,在eclipse下面,打开DDMS可以再data目录下的data中找到工程,然后打开工程下的files目录,可看到你的文件。下面是一个文件读写的小例子:
package com.example.databasetest;
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.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Fileread extends Activity{
EditText editneiron;
Button butstore;
Button butlook;
String fileurl="test.txt";//文件名
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.filereaderorwrite);//加载布局文件
editneiron=(EditText)
findViewById(R.id.textneiron);
butstore=(Button)
findViewById(R.id.butstore);
butlook=(Button)
findViewById(R.id.textread);//组件
butstore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
writeDate();//调用写方法
}
});
butlook.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
readfile();//调用读方法
}
});
}
public void writeDate()//写方法
{
FileOutputStream fileoutputstream=null;//写代表的是输出,所以用的是输出流
try {
fileoutputstream=openFileOutput(fileurl, Context.MODE_WORLD_WRITEABLE);
//Context.MODE_WORLD_WRITEABLE参数,和文件的读用的参数不一样
byte[] by=editneiron.getText().toString().getBytes();
fileoutputstream.write(by);
fileoutputstream.flush(); //记得fluseh()一下,使全部写入
Toast.makeText(this,"文件写入完成!",Toast.LENGTH_LONG).show();//信息提示
} catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
fileoutputstream.close();//最后的最后,记得关闭
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void readfile()//读方法
{
FileInputStream fileinputstream=null;
try {
fileinputstream=this.openFileInput(fileurl);//读入流
byte[] bys=new byte[512];//每次读的多少,可提高读入效率
int count=-1;
StringBuffer stb=new StringBuffer("读出的内容是:");
while((count=fileinputstream.read(bys))!=-1)
{
stb.append(new String(bys,0,count));
}
Toast.makeText(this,stb.toString(),Toast.LENGTH_LONG).show();//提示
} catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
fileinputstream.close();//记得关闭读入流
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
许多需要长期保存的配置文件或数据量不大却需要保存的文件,可以不使用Sqlite,直接使用文件读写,然后对读出的字符串进行处理,也是很方便的。