在Android中将字符串读写到内部存储的方法

6
我想要写入文件并从中读取。使用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;
}

2
你想在read()中返回buffer.toString()!(顺便说一句,“String Read;”似乎在你的代码片段中缺失,但是你不应该使用大写的非静态变量。) - Stefan
那么我该怎么做呢?可能一个代码片段会有所帮助。 - Atinder
4
请将您的read()方法中的最后一行改为"return buffer.toString();",并在while循环之前添加"String read;"以定义变量"read"。另外,您应该使用小写字母,例如"String line;",而且在while循环中使用"reader.readLine()"时,也需要将其转换为小写字母。 - Stefan
我实际上在我的类中将Read定义为一个静态变量。 - Atinder
2个回答

2

在read方法中使用return buffer.toString()解决了问题。感谢Stefan。


很抱歉长时间未回复此帖。我从“asset”文件夹中读取了一个文件,然后使用“FileOutputStream”写入该文件。我的问题是,“FileOutputStream”保存文件的路径是什么? - Saad Saadi

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接