Search code examples
javaandroidfileiofileoutputstream

Android studio, open a file , continuously write and then close


I have code that is generating data every second and displaying onscreen. This all works fine but I want to create a log file of all the data to analyze later.

I can open/write/close a file each time data is created but I am unsure of how much processing power this is using as it is continually opening and closing the file

  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();

I would prefer to have the file open when the start button is clicked.

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();
                }

but when it comes to closing the file, no options for .close() appear when out is typed

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;

            }

Does all the open/write/close need to be together or is it possible to

***open file***
-----
Cycle through all the data
-----
***Close file***

Solution

  • You should store a link to your FileOutputStream on top level in your class.

    Example to your code:

    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;
            }
    }