2012-08-28 40 views
5

我想写入文件,然后从中读取。在使用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; 
} 
+2

你想在read()中返回buffer.toString()! (顺便说一下,“字符串读取”似乎在您的代码片段中丢失,但不应该使用大写的非静态变量。) – Stefan

+0

那么我该怎么做? 代码片段可能会有所帮助。 – Atinder

+4

返回buffer.toString()作为read()方法的最后一行。并添加“读取字符串”在你的while循环之前的某个地方定义“Read”变量。你应该使用小写,例如字符串行; while((line = reader.readLine())!= null)buffer.append(line +“\ n”); – Stefan

回答

2

return read.toString()在read方法中解决了这个问题。 谢谢Stefan。

+0

很抱歉让这条线长时间重新生活。我从'asset'文件夹中读取一个文件,然后使用'FileOutputStream'写入该文件。我的问题是'FileOutputStream'保存的文件路径。 –