Java 如何计算文件中的数字总和?

Java 如何计算文件中的数字总和?,java,android,filereader,Java,Android,Filereader,我想在TextView中显示从文件中添加的所有数字的总和,目前它只读取/显示文件中的最后一个数字 这是我当前用于写入文件的代码: total.setText(total.getText()); try { FileOutputStream fos = openFileOutput("TotalSavings", Context.MODE_PRIVATE); fos.write(

我想在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();
        }               
    }

有人能告诉我怎么做吗?

假设这行上只有一个整数,你就不能这样做吗

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-total
更改为
double-total
,将
Integer.parseInt()
更改为
double.parseDouble()
。此外,如果行中的字符多于数字/小数,请尝试使用以下方法仅删除并使用数字,并确保行中有内容:

if (inputString.length() > 0) {
    String line = inputString.replaceAll("[^0-9.]", "");
    total = total + Double.parseDouble(line);
}

使用
Scanner
从文件中读取数据。这是“谢谢”的副本,但数字不是整数,它们是价格,例如18.95英镑、50英镑等。所以我必须将其更改为双精度吗?是的,只要您没有任何其他字符,如:£就可以了。如果您这样做,您将需要去掉任何其他字符,以确保从
字符串
转换数据类型成功。@OlympicBeast我编辑了我的答案,为您指明了正确的方向。如果您需要任何澄清,请告诉我。如果我的回答对你有帮助,请接受。很抱歉刚才看到你的编辑。我还在Eclipse LogCat上看到这个错误:java.lang.IllegalStateException:无法执行activity@OlympicBeast听起来好像从那个错误你有一个空值的地方。确保所有变量都已初始化且一致。这可能是因为您试图从空值(空行)解析双精度/整数。请参见我的编辑以及去掉货币符号。使用
replaceAll()
,您只能去掉数字/小数。