java - Android studio,打开一个文件,不断写入然后关闭

标签 java android file io fileoutputstream

我有每秒生成数据并显示在屏幕上的代码。 这一切都工作正常,但我想创建所有数据的日志文件以便稍后分析。

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

  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***

最佳答案

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

关于java - Android studio,打开一个文件,不断写入然后关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60281375/

相关文章:

c++ - 连接文件而不复制其内容

c++ - 如何将结构数组写入二进制文件并再次读取?

python - 在 python 3.x 中有效地搜索多个文件的关键字的最佳方法?

java - 需要帮助来运行 RMI Registry

java - Android如何获取JSONObject中的int类型

java - 如何在不使用条件的情况下创建返回 1 或 0 的方法?

android - 动态设置OnClickListener

java - 将抽屉导航显示/隐藏机制应用于侧边栏布局

java - Java 9+中如何安全访问类路径中所有资源文件的URL?

php - 将数组从 android 传递到 php 在 android 4.1 上失败,但在 android 5+ 上成功