要把信息写入文本中进行固化存储是开发中经常用到的一种方法,下面是具体的操作流程,(文中只涉及核心代码,不是完整的项目)。
try{
File file = new File("mnt/sdcard/newfile.txt");? //先New出一个文件来
FileOutputStream fos = new FileOutputStream(file); //然后再New出一个文件输出流,
String content = name+":"+pwd;? ? ? ? ? ? ? ? ? ? //这里是要写入的内容,我这里要写入的内容为用户name和一个“:”,以及密码
fos.write(content.getBytes());? ? ? ? ? ? ? ? ? ? //用文件输出流的Write方法写入注意,Write方法只能写入字节,所以要将content使用getBytes方法获得字节流传入,
fos.flush();? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //flush输出流
fos.close();? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //close输出流
}
catch (Exception e) {? ? ? ? ? ? ? ? ? ? ? ? ? ? //以上代码是有风险的,需要try,catch
?e.printStackTrace();
}
以上是比较常用的方法,这时文件的输出流可以轻松直接创建,但是如果在安卓开发过程中,要把文件写进Rom中,这种方法就不太好用了,我们创建文件输出流通常是使用安卓上下文context中的一个方法来完成的。
public class savepwd {? ? ? ? ? ? ?
?private Context context;
?public savepwd(Context context) {? ? //首先我们为类创建一个上下文,并用构造函数进行初始化
? this.context = context;
?}
?public void saveToRom(String name,String pwd){
?try{
?FileOutputStream fos = context.openFileOutput("config.txt",Context.MODE_PRIVATE);
?//使用context中的OpenFileOutput方法来创建一个文件输出流
? ? ? ? String content = name + ":" + pwd;
?//这里是要写入的内容
?fos.write(content.getBytes());
?fos.fulsh();
?fos.close();
?}
?catch(Exception e){
?Toast.makeText(context,"ROM文件写入失败",Toast.LENGTH_LONG).show();
?//打印错误提示
?e.printStackTrace();
?}
?}
}