我想要写入文件并从中读取。使用openFileOutput(..,..)方法时,我得到了“此方法未定义”,因为它是抽象方法。然后我尝试使用getBaseContext()传递上下文,警告消失了,但读取输出时没有得到结果。我还尝试在构造函数中将上下文作为参数传递,但这也没有帮助。我想编写静态方法,这样我就不必每次实例化该类,而静态不是原因,因为我也尝试过不使用静态方法。以下代码片段:
需要在使用内部存储时指定路径吗? 写入内部存储文件需要授权吗?(我已经包含了在外部存储器上写入的权限)
需要在使用内部存储时指定路径吗? 写入内部存储文件需要授权吗?(我已经包含了在外部存储器上写入的权限)
public static void write (String filename,Context c,String string) throws IOException{
try {
FileOutputStream fos = c.openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String read (String filename,Context c) throws IOException{
StringBuffer buffer = new StringBuffer();
FileInputStream fis = c.openFileInput(filename);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
if (fis!=null) {
while ((Read = reader.readLine()) != null) {
buffer.append(Read + "\n" );
}
}
fis.close();
return Read;
}