无法让Android将数据附加到.txt文件

时间:2015-12-07 04:36:57

标签: java android text append filewriter

我在这里很新,并且一直关注所有我能找到的程序,以便在计时器用完时将一系列数字(根据按下按钮的频率确定)附加到.txt文件,但无济于事 - 我不确定我错过了什么......应用程序首先在下载文件夹中创建一个带有模板的.txt文件:

String initialTemplate ="\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"10\",\"11\",\"12\"";
    File path = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOWNLOADS);
    File file = new File(path, filename+".txt");
    try {
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(initialTemplate.getBytes());
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

然后当countdowntimer对象完成并重新启动/结束时,它会触发类writeresults()以附加值:

if (CountsRemaining < 1){
                textViewTime.setText("00:00:00");
                cancel();
                    writeResults();
                finishcount();
            } else {
                //append data
                    writeResults();
                //Clear all variables
                clearCounts();
                start();
            }

重要的是,实际编写数据,这是什么不起作用:

public void writeResults(){
String Message = Count1 + ", " + Count2 + ", " + Count3 + ", " + Count4 + ", " + Count5 + ", " +
        Count6 + ", " + Count7 + ", " + Count8 + ", " + Count9 + ", " + Count10 + ", " + Count11 + Count12;
FileWriter writer;
try {
    File path = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_DOWNLOADS);
    File file = new File (path + filename+".txt");
    writer = new FileWriter(file, true);
        writer.append(Message);
        writer.append("this is a writing test message");
        writer.close();
        Toast.makeText(getApplicationContext(), "Data Saved", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

知道我可能缺少什么吗?参数Δ

1 个答案:

答案 0 :(得分:0)

问题出在这一行:

File file = new File (path + filename+".txt");

如果您在创建文件时查看第一个代码,应该是这样的:

 File file = new File (path, filename+".txt");
相关问题