Android studio,打开文件,连续写入然后关闭

问题描述 投票:0回答:2

我有每秒生成数据并在屏幕上显示的代码。这一切都很好,但是我想创建一个包含所有数据的日志文件以供以后分析。

每次创建数据时我都可以打开/写入/关闭文件,但是由于不断打开和关闭文件,因此我不确定使用多少处理能力

  String data= reading1","+reading2+","+time +"/n";
        try {
            FileOutputStream out = openFileOutput("data.csv", Context.MODE_PRIVATE);
            out.write(data.getBytes());
            out.close();
        } catch (Exception e) {
            e.printStackTrace();

我希望在单击开始按钮时打开文件。

if ( v.getId() == R.id.start ){
                // checks which button is clicked
                Log.d("dennis", "Scan working"); //logs the text
                // open a file
                try {
                    FileOutputStream out = openFileOutput("data.csv", Context.MODE_PRIVATE);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

但是在关闭文件时,键入out时不会显示.close()选项

if ( v.getId() == R.id.stop ){
                // checks which button is clicked

                out. // no valid options appear
                messageValue.setText(R.string.stopButtonText);// changes the hallo world text
                readNoRead=false;

            }

是否所有打开/写入/关闭操作必须在一起,或者是否可以

***open file***
-----
Cycle through all the data
-----
***Close file***
java android file io fileoutputstream
2个回答
0
投票

绝对有可能在不关闭文件的情况下将文件全部打开,处理和关闭。

您的out变量未显示任何方法建议,因为尚未在该块中定义该变量。换行

FileOutputStream out = openFileOutput("data.csv", CONTEXT.MODE_PRIVATE);

out = openFileOutput("data.csv", CONTEXT.MODE_PRIVATE); 

,然后将FileOutputStream out;添加到第一个if语句上方的行中(块外部)。

[您可能还希望研究'try-catch-finally'或'try with resources'作为在try-catch块中关闭文件的选项。


0
投票

您应该在班级的顶层存储指向FileOutputStream的链接。您的代码示例:

FileOutputStream out;
void clickStart() {
    if (v.getId() == R.id.start){
        // checks which button is clicked
        Log.d("dennis", "Scan working"); //logs the text
        // open a file
        try {
            out = openFileOutput("data.csv", Context.MODE_PRIVATE);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
}

void writeData() {
    String data= reading1+","+reading2+","+time +"/n";
    try {
        out.write(data.getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

void clickStop() {
    if (v.getId() == R.id.stop) {
        try {
            out.close();
        } catch(IOException e) {
            e.printStackTrace();
        }
        messageValue.setText(R.string.stopButtonText);// changes the hello world text
            readNoRead=false;
        }
}
© www.soinside.com 2019 - 2024. All rights reserved.