有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java 安卓。所容纳之物ContextWrapper。openFileOutput空指针异常

我的目标是写入和读取文件以保存应用程序的设置。这些设置将由用户配置并保存到名为saved_settings的文件中。文本

我的方法是有一个单独的java类来处理这个问题,我会在需要时引用这个类及其方法

现在我的代码在fos=openFileOutput(文件名,MODE_PRIVATE)处中断

这是因为我还没有创建文件。它总是给我一个空指针异常,我似乎不明白为什么

提前感谢您的帮助

我调用Java类来读或写

package com.example.tipcalculator;

import 安卓.widget.Toast;

import 安卓x.appcompat.app.AppCompatActivity;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/*
ReadWrite is a java class that retrieves and saves data to a file
 */
public class ReadWrite extends AppCompatActivity {
 //"saved_settings.txt" or "tip_data.txt"

    /**
     * Creates ReadWrite Object
     */
    public ReadWrite() {

    }

    /**
     * Writes to file
     * @param text
     * @param fileName
     */
    public void writeToFile(String text, String fileName) {
        FileOutputStream fos = null;
        try {
            fos = openFileOutput(fileName, MODE_PRIVATE);
            fos.write(text.getBytes());

            Toast.makeText(this, "Saved to " + getFilesDir() + "/" + fileName,
                    Toast.LENGTH_LONG).show();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Reads from file
     * @param fileName
     * @return
     */
    public String readFromFile(String fileName) {
        String text = new String();

        FileInputStream fis = null;

        try {
            fis = openFileInput(fileName);
            InputStreamReader isr = new InputStreamReader(fis);
            BufferedReader br = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();

            while ((text = br.readLine()) != null) {
                sb.append(text).append("\n");
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return text;
    }


}

从“保存”按钮触发的代码

private void saveSettings() {
    String settings = boxMode + "," + desc1TB.toString() + "," + perc1TB.toString() + "," + desc2TB.toString() + "," + perc2TB.toString() + "," + desc3TB.toString() + "," + perc3TB.toString() + "," + desc4TB.toString() + "," + perc4TB.toString();
    readWrite.writeToFile(settings, "saved_settings.txt");
}

共 (0) 个答案