0

我有一个 android 应用程序正在将值写入该应用程序还创建的文件。我能够写入文件,然后再次从文件中读取。但是,一旦该活动完成,文件似乎现在已经消失了,或者丢失了它的值。

我知道你不能通过资源管理器浏览文件,除非你 root 手机和/或以特定用户身份运行 adb 服务器。

这是我写入文件的代码: public void savePrices(View view) { FileOutputStream outputStream;

        File getFilesDir = this.getFilesDir();
        File filePathOne = new File(getFilesDir, filename);
        try {
            outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
            for (int i = 0; i < priceArray.length; i++) {
                outputStream.write(String.format("%.2f\n", priceArray[i]).getBytes());
            }

            Toast.makeText(this, "Prices saved successfully!", Toast.LENGTH_SHORT).show();
            outputStream.close();
            } catch (Exception e) {
            e.printStackTrace();
        }

这是我读取文件的代码:

public void loadPrices(View view) {
        int i = 0;
        final InputStream file;
        BufferedReader reader;
        try{
            file = getAssets().open(filename);
            reader = new BufferedReader(new InputStreamReader(file));
            String line = reader.readLine();
            while(line != null){
                line = reader.readLine();
                priceArray[i] = Double.parseDouble(line);
                i++;
            }
        } catch(IOException ioe){
        ioe.printStackTrace();

        hamburgerPriceText.setText(String.format("%.2f", priceArray[0]));
        hotDogPriceText.setText(String.format("%.2f", priceArray[1]));
        chipsPriceText.setText(String.format("%.2f", priceArray[2]));
        beerPriceText.setText(String.format("%.2f", priceArray[3]));
        popPriceText.setText(String.format("%.2f", priceArray[4]));

        Toast.makeText(this, "Prices loaded successfully!", Toast.LENGTH_SHORT).show();

        }catch (NumberFormatException e) {
            Log.e("Load File", "Could not parse file data: " + e.toString());
        }
    }

在调用设置数组中的值并将值保存到文件中的 save 方法后,我运行一个 clear 方法来删​​除活动字段和数组中的所有值。因此,当我运行 read 方法并填充活动上的字段时,我知道这些值来自读取文件。这是我知道我正在成功保存和读取文件的唯一方法。

我的问题是如何使其永久化?如果我关闭保存值的活动,然后立即运行 read 方法,所有值都是 0。

有什么我想念的吗?如何写入文件,以便在活动关闭或应用程序完全关闭时,我仍然可以保留这些值?

4

1 回答 1

1

这是我读取文件的代码:

该代码中没有任何内容可以读取文件。它正在从您的应用程序资产中读取一些内容。此外,出于某种原因,它只会在您遇到异常时更新 UI。

因此,当我运行 read 方法并填充活动上的字段时,我知道这些值来自读取文件。

不,它们来自您应用程序的资产,并且您只有在拥有IOException.

我的问题是如何使其永久化?

步骤#1:实际从文件中读取。由于您openFileOutput()用于写入文件,因此请用于openFileInput()从文件中读取。

第 2 步:当您成功读取数据时更新 UI,而不是catchIOException.

于 2015-08-09T22:12:21.503 回答