2010-09-02 133 views
7

这是完美的描述here如何做到这一点,唯一的问题:他不知道的功能openFileOutput();Android:如何在内部存储器上存储数据?

private void saveSettingsFile() { 
      String FILENAME = "settings"; 
      String string = "hello world!"; 

      FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); //openFileOutput underlined red 
      try { 
      fos.write(string.getBytes()); 
      fos.close(); 
      } catch (IOException e) { 
      Log.e("Controller", e.getMessage() + e.getLocalizedMessage() + e.getCause()); 
      } 
} 

这些都是我进口相关的包:

import java.io.FileOutputStream; 
import java.io.IOException; 
import android.content.Context; 
+0

你能分享logcat的误差输出一活动的内? – 2010-09-02 14:35:44

+0

我只注意到“openFileOutput”是加下划线的红色。 Eclipse要求我在我的课堂上创建一个所谓的方法,我无意中这样做了。现在我删除了这个方法存根,并且“openFileOutput”再次被强调为红色。 – OneWorld 2010-09-02 14:44:16

+0

@Konstantin:它比逻辑问题更为合理。所以logcat还没有帮助。知道我甚至不能编译它。 – OneWorld 2010-09-02 14:51:13

回答

2

看一看使用FileOutputStrem从dev.android.com的例子的this example。它应该给你一个如何正确使用它的想法。

+0

谢谢你。我会仔细看看的。不过,我仍然希望得到这5条线路的工作。我的意思是我上面提到的文件的作者不可能是根本错误的。 – OneWorld 2010-09-02 15:09:58

+4

您需要在上下文中调用openFileOutput。尝试'context.openFileOutput()' – fredley 2010-09-02 15:13:33

+0

好的,好建议。但是我没有变量或对象“​​上下文”。我如何创建或获取它? – OneWorld 2010-09-02 15:19:46

1

声明此方法的类定义为“静态”。这就是为什么它抛出错误。从类定义和宾果中删除静态...

0

只需添加一个“try catch”块并将它们放在这之间。

这样的:

private void saveSettingsFile(String FILENAME, String data) { 

    FileOutputStream fos; 
    try { 
     fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); 
     fos.write(data.getBytes()); 
     fos.close(); 
    } catch (FileNotFoundException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } // openFileOutput underlined red 
    catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

当存在线下红线。首先检查该行是全sentense或仅sen​​tense的右侧下(即等号后)。

如果它涵盖了整条生产线,那么它必须修复了一些bug ..

或者如果它只是sentense右侧下......那么就必须要一些异常处理的事情。

如果你不知道它会产生什么类型的异常...
不要害怕,只是写在try块中的所有代码(尝试{}),然后添加一个catch,并通过内部的异常对象赶上。现在它很好..

像这样:

try 
    { 
    ...........your code 
    ...... 
    } 
    catch(Exception e) 
    { 
    e.printstacktrace(); 

    } 

现在个个都是精品。

谢谢

0

openFileOutput是Context对象的一种方法。并且不要忘记添加finally子句来关闭流。 Bellow是一个例子(由于Android的原因,Java 6有点笨拙)。

String data = "Hello"; 
FileOutputStream fos = null; 
try { 
    fos = mContext.openFileOutput(FILENAME, Context.MODE_PRIVATE); 
    fos.write(data.getBytes(Charset.defaultCharset())); 
} catch (IOException e) { 
    e.printStackTrace(); 
} finally { 
    if (fos != null) { 
     try { 
      fos.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

mContext变量应该被以上定义的某个地方和类似mContext = getApplicationContext初始化()如果您是

相关问题