2012-02-27 60 views
0

我目前正在将应用程序中的多个活动类的单个文件保存到单个文件中。每个活动类具有相同的函数WriteToFile。Android,使用继承写入文件

public void WriteToFile(String info) { 

    FileOutputStream FoutS = null; 
    OutputStreamWriter outSW = null; 

    try { 

     FoutS = openFileOutput("file.txt", MODE_PRIVATE); 
     outSW = new OutputStreamWriter(FoutS); 
     outSW.write(info); 
     outSW.flush(); 
    } 

    catch (Exception e) { 
    } 

    finally { 
     try { 
      outSW.close(); 
      FoutS.close(); 
     } catch (IOException e) { 
     } 
    } 
} 

我一直在试图创建一个单独的类,它拥有这个功能写(读),以文件,但我一直没能没有得到错误。

我觉得功能需要有通过传递给将writeToFile无效像背景...

//Changes to this line 
public void WriteToFile(String info, Context context) { 

    FileOutputStream FoutS = null; 
    OutputStreamWriter outSW = null; 

    try { 
         //Changes to this line 
     FoutS = context.openFileOutput("file.txt", MODE_PRIVATE); 
     outSW = new OutputStreamWriter(FoutS); 
     outSW.write(info); 
     outSW.flush(); 
    } 

    catch (Exception e) { 
    } 

    finally { 
     try { 
      outSW.close(); 
      FoutS.close(); 
     } catch (IOException e) { 
     } 
    } 
} 

如果这是正确的我会正确地传递上下文?

String msg = "This is a message"; 

WriteToFile(msg, this); 

它不工作,所以我做错了什么。

+0

如果你可以发布堆栈跟踪,你会发现这将有所帮助(你可能想要删除你的catch语句以确保异常被抛出堆栈)。 – tomtheguvnor 2012-02-27 21:14:28

回答

0

你应该用你的上下文来调用方法

context.openFileOutput("file.txt", context.MODE_PRIVATE); 

你写的是什么已经没有意义,或者从你的意思远。