public class FileService {
private Context context;
public void save(String filename, String filecontent) throws Exception {
//Context.MODE_PRIVATE,文件私有保存模式。保存的文件不能被其他应用所访问,而且以覆盖的形式保存文件
FileOutputStream fileOutputStream = context.openFileOutput(filename, Context.MODE_PRIVATE);
fileOutputStream.write(filecontent.getBytes());
fileOutputStream.flush();
fileOutputStream.close();
}
}
要么路径不对,要么文件不存在。写之前最好判断一下文件是否存在。
context 你没有传如这个参数,没有对它进行初始化。所以会报空指针一场。
同楼上,context = getApplicationContext();加上这句
谢谢楼上各位,问题确实如此,我是新手,所以这个问题弄了很久。
补充一下我昨天自己的解决方法,简单的方法,只是分享。
————————————————————————————————————————————————
我自己指定并创建了和openFileOutput()方法相同的路径的文件,然后使用字节输出流把文字信息存入文件中。
public void save(String filename, String filecontent) throws Exception {
//Context.MODE_PRIVATE,文件私有保存模式。保存的文件不能被其他应用所访问,而且以覆盖的形式保存文件
File file = new File("/data/data/com.jmu.cs1412.hzl.myapplication/files",filename);
file.createNewFile();
file.setWritable(true,true);
FileOutputStream fileOutputStream = new FileOutputStream(file,true);
fileOutputStream.write(filecontent.getBytes());
fileOutputStream.flush();
fileOutputStream.close();
}
——————————————————————————————————————————————
当然还有最方便的方法,直接用openFileOutput()方法,我没有成功的原因如楼上所说,是没有初始化 context。现已更正。
public void save(String filename, String filecontent) throws Exception {
//Context.MODE_PRIVATE,文件私有保存模式。保存的文件不能被其他应用所访问,而且以覆盖的形式保存文件
FileOutputStream fileOut = context.openFileOutput(filename,Context.MODE_PRIVATE);
fileOut.write(filecontent.getBytes());
fileOut.close();
}
再次谢谢楼上几位的帮助