【问题标题】:Android, write to file using inheritanceAndroid,使用继承写入文件
【发布时间】:2012-02-27 20:47:52
【问题描述】:

我目前正在将消息从我的应用程序中的多个活动类保存到单个文件中。每个活动类都有相同的函数WriteToFile。

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 void,例如...

    //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);

它不起作用,所以我做错了。

【问题讨论】:

  • 如果您可以发布您看到的堆栈跟踪,这将有所帮助(您可能需要删除您的 catch 语句以确保异常被抛出堆栈)。

标签: android writetofile


【解决方案1】:

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

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

你写的没有意义,或者与你的意思相去甚远。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    相关资源
    最近更新 更多