7

这里完美地描述如何做,唯一的问题:他不知道功能openFileOutput()

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;
4

4 回答 4

2

从 dev.android.com 的示例中查看使用 FileOutputStrem 的示例。它应该让您了解如何正确使用它。

于 2010-09-02T14:59:36.593 回答
1

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

于 2012-03-16T14:14:18.247 回答
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();
    }
}

当线下有红线时。首先检查该线是在全句下方还是仅在句的右侧。(即在等号之后)。

如果它涵盖了整条线,那么它必须修复一些错误..

或者如果它只在句子的右边...那么它一定想要一些异常处理的东西。

如果你不知道它可能会产生什么类型的异常......
不要害怕,只需将所有代码写在一个 try 块(try{})中,然后添加一个 catch 并在 catch 中传递一个 Exception 对象......现在很好..

像这样 :

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

  }

现在一切都很好。

谢谢

于 2013-08-02T12:07:23.720 回答
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() 一样初始化,如果你在一个活动里面

于 2016-08-22T16:48:02.347 回答