1

我想在 TextView 中显示从文件中添加的所有数字的总和,目前它只是读取/显示文件中的最后一个数字。

这是我当前写入文件的代码:

total.setText(total.getText());                            
        try {
            FileOutputStream fos = openFileOutput("TotalSavings", Context.MODE_PRIVATE);
            fos.write(total.getText().toString().getBytes());
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

这是我当前从文件中读取的代码:

public void savingstotalbutton(View view) {

        try {
            BufferedReader inputReader = new BufferedReader(new InputStreamReader(
                    openFileInput("TotalSavings")));
            String inputString;
            StringBuffer stringBuffer = new StringBuffer();                
            while ((inputString = inputReader.readLine()) != null) {
                stringBuffer.append(inputString + "\n");
            }
            savingstotaltext.setText(stringBuffer.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }               
    }

谁能告诉我该怎么做?

4

1 回答 1

2

假设线上唯一的东西是一个整数,你不能做这样的事情吗?

public void savingstotalbutton(View view) {

    int total = 0;

    try {
        BufferedReader inputReader = new BufferedReader(new InputStreamReader(
                openFileInput("TotalSavings")));
        String inputString;
        StringBuffer stringBuffer = new StringBuffer();                
        while ((inputString = inputReader.readLine()) != null) {
            //stringBuffer.append(inputString + "\n");
            total = total + Integer.parseInt(inputString);
        }
        //savingstotaltext.setText(stringBuffer.toString());
        savingstotaltext.setText(String.ValueOf(total));
    } catch (IOException e) {
        e.printStackTrace();
    }               
}

编辑:评论中每个问题的扩展答案

如果您使用小数,只需更改int totaltodouble totalInteger.parseInt()to 即可。Double.parseDouble()此外,如果行上的字符多于数字/小数,请尝试使用以下内容仅删除并使用数字,并确保行上有内容:

if (inputString.length() > 0) {
    String line = inputString.replaceAll("[^0-9.]", "");
    total = total + Double.parseDouble(line);
}
于 2012-11-06T14:50:10.107 回答