java - Java 类或 Android Activity 中的 Save File 方法?

标签 java android internal-storage

我有一个应用程序,它将获取用户的分数,将其保存到当前分数列表,然后显示所有分数。 saveScores 方法位于 HighScores 类中,但将从用户输入姓名的 Activity 中调用。

因为该方法位于 java 类中,而不是 Android Activity 中,所以我无法让代码正常工作。我尝试了两个选项,每个选项都会给出不同的错误:

选项 1:

FileOutputStream fileout=openFileOutput("highScores.txt", Context.MODE_PRIVATE);
//ERROR: The method openFileOutput(String, int) is undefined for the type HighScore.

选项 2:

FileOutputStream fileout=openFileOutput("highScores.txt", MODE_PRIVATE);
//ERROR: MODE_PRIVATE cannot be resolved to a variable

选项 1 正是 tutorial 中的代码我使用过,运行时有效,所以应该是正确的选择。但由于 java 类中没有上下文,我认为这就是它遇到麻烦的地方。 除了将整个方法移至 Activity 中之外,还有什么方法可以使这项工作正常进行吗?

就其值(value)而言,这是整个 saveFile 方法:

public void saveScores(Context context, ArrayList<Score> scores){
    // save to file
    try{
        String allScores ="";
        FileOutputStream fileout=openFileOutput("highScores.txt", Context.MODE_PRIVATE);    // The line in question.
        OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);

        for (int i=0; i<scores.size(); i++)
            allScores += ((i+1)+". "+scores.get(i).toString()+"\n");

        outputWriter.write(allScores);
        outputWriter.close();
    }catch(FileNotFoundException e){
         System.out.println("SaveScores ERROR: File Not Found.");
    }catch(IOException e){
         System.out.println("SaveScores ERROR: See Stack Trace below.");
         e.printStackTrace();
    }

最佳答案

这个:

FileOutputStream fileout=openFileOutput("highScores.txt", Context.MODE_PRIVATE);

应该使用:

FileOutputStream fileout=context.openFileOutput("highScores.txt", Context.MODE_PRIVATE);

您将得到:

FileOutputStream fileout=openFileOutput("highScores.txt", Context.MODE_PRIVATE);
//ERROR: The method openFileOutput(String, int) is undefined for the type HighScore.

因为它正在寻找openFileOutput你的 HighScore 类中的方法,它永远不会找到,因为你没有/不需要一个方法,因为它是 Context 的一部分。

关于java - Java 类或 Android Activity 中的 Save File 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27384225/

相关文章:

java - 如何根据 GET 请求初始化 bean 属性?

java - 对 Xodus 的非独占读取权限

java - OSGi:当某个服务可用时,DS 服务消费者是否会同步收到通知

java - Android 如何为 UI 事件编写一个简单的计时器?

android - kotlin kdoc 中的引用资源不可点击

android - App更新时是否删除了内部存储文件?

ios - 如何从iPhone到Mac提取IPA文件?

java - 获取图像内部存储的文件路径

java - OpenLDAP 仅返回密码过期的警告

android - 在 Android 中向 ImageView 添加文本