【问题标题】:Android studio, open a file , continuously write and then closeAndroid studio,打开一个文件,不断写入然后关闭
【发布时间】:2020-06-02 12:03:40
【问题描述】:

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

我可以在每次创建数据时打开/写入/关闭文件,但我不确定这使用了多少处理能力,因为它会不断打开和关闭文件

  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


【解决方案1】:

您应该在班级的顶层存储指向您的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;
        }
}

【讨论】:

  • 非常感谢您提供这些信息。我已经启动并运行了打开和关闭文件。我刚刚完成另一项活动的写作部分,它应该很快就能完美运行。
【解决方案2】:

完全可以在一个块中打开、处理和关闭文件而无需关闭文件。

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

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

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

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

您可能还想查看“try-catch-finally”或“使用资源尝试”作为在 try-catch 块中关闭文件的选项。

【讨论】:

  • 非常感谢您提供这些信息。这个解决方案让我更清楚了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多