我想写入文件,然后从中读取。在使用openFileOutput(..,..)方法时,我发现这个方法没有被定义,因为它是一个抽象方法。然后我用getBaseContext()传递上下文来尝试它。并警告已关闭,但我没有看到输出结果。我也尝试在构造函数中传递上下文作为参数,但这也没有帮助。我想编写静态方法,以便我不必每次都实例化类,静态不是原因,因为我也没有尝试过。代码片段如下所示。将字符串写入Android中的内部存储器
即使在使用内部存储器时,是否需要指定任何路径? 是否有任何权限在内部存储上写入文件? (我已包含在外部存储上写入的权限)
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;
}
你想在read()中返回buffer.toString()! (顺便说一下,“字符串读取”似乎在您的代码片段中丢失,但不应该使用大写的非静态变量。) – Stefan
那么我该怎么做? 代码片段可能会有所帮助。 – Atinder
返回buffer.toString()作为read()方法的最后一行。并添加“读取字符串”在你的while循环之前的某个地方定义“Read”变量。你应该使用小写,例如字符串行; while((line = reader.readLine())!= null)buffer.append(line +“\ n”); – Stefan