【发布时间】:2012-08-28 10:12:42
【问题描述】:
我想写入一个文件,然后从中读取。在使用 openFileOutput(..,..) 方法时,我发现此方法未定义,因为它是一种抽象方法。然后我尝试使用 getBaseContext(); 传递上下文;并且警告已关闭,但我在读取输出时没有得到结果。我还尝试在构造函数中将上下文作为参数传递,但这也无济于事。我想编写静态方法,这样我就不必每次都实例化类,而静态不是原因,因为我也尝试过没有它。代码是sn-p,如下所示。
即使在使用内部存储时,我是否需要指定任何路径? 在内部存储上写入文件是否需要任何权限? (我已经包含了在外部存储上写入的权限)
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() ! (顺便说一句,您的代码 sn-p 中似乎缺少“String Read;”,但是您不应该使用大写的非静态变量。)
-
那我该怎么做呢?一个代码 sn-p 可能会有所帮助。
-
返回 buffer.toString() 作为 read() 方法的最后一行。并添加“字符串读取;”在你的while循环之前的某个地方定义“读取”变量。你应该使用小写,例如字符串线; while( (line = reader.readLine()) != null) buffer.append(line + "\n");
-
谢谢!我实际上在我的类中将 Read 定义为静态变量。
标签: android fileoutputstream file-io