【问题标题】:Can't Get Android to Append Data to .txt file无法让 Android 将数据附加到 .txt 文件
【发布时间】:2016-03-11 15:21:20
【问题描述】:

我在这里很新,并且一直在关注我可以找到的所有内容,让我的程序在计时器用完时将一系列数字(由按下按钮的频率确定)附加到 .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();
    }

然后当倒计时对象完成并重新启动/结束时,它会触发类 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();
    }
}

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

【问题讨论】:

    标签: java android text append filewriter


    【解决方案1】:

    问题出在这一行:

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

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

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

    【讨论】:

    • 更好...它并没有完全按照我想要的方式附加,但是有一个额外的文件以“null.txt”的名称显示,其中包含应该已经进入的数据.在那之后,我意识到我只是忘记了导入字符串文件名,因为它是在不同的活动中作为额外的意图而来的。感谢您的帮助!
    • 哦,我假设你已经初始化了 filename 变量。很高兴能帮到你。
    猜你喜欢
    • 2015-11-25
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多