【问题标题】:Writing and Reading String to an internal storage in Android在Android中将字符串写入和读取到内部存储
【发布时间】: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


【解决方案1】:

return buffer.toString() in read 方法解决了这个问题。 谢谢斯特凡。

【讨论】:

  • 很抱歉让这个帖子在很长一段时间后重新上线。我从asset 文件夹中读取了一个文件,然后使用FileOutputStream 编写了该文件。我的问题是FileOutputStream保存的文件路径是什么。
【解决方案2】:

在内部存储上写入文件是否需要任何权限?

"You don’t need any permissions to save files on the internal storage. Your application always has permission to read and write files in its internal storage directory."

您可能会看到一些帖子声明使用:“android.permission.WRITE_INTERNAL_STORAGE”

There is no such permission; “WRITE_INTERNAL_STORAGE”

【讨论】:

    猜你喜欢
    • 2015-01-31
    • 2015-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 2011-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多