Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a file, if it doesn't exist then create

Honestly, I've searched a lot do this task so I ended up trying various methods but nothing worked until I ended up on this code. It works for me perfectly like it should, so I do not want to change my code.

The help I need is to put this code in a such a way that it begins to read a file, but if it the file doesn't exist then it will create a new file.

Code for saving data:

String data = sharedData.getText().toString();
try {
        fos = openFileOutput(FILENAME, MODE_PRIVATE);
        fos.write(data.getBytes());
        fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Code for loading data:

FileInputStream fis = null;
        String collected = null;
        try {
            fis = openFileInput(FILENAME);
            byte[] dataArray = new byte [fis.available()];
            while (fis.read(dataArray) != -1){
                collected = new String(dataArray); 
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

So If I add the saving data code in to the "FileNotFoundException" catch of the loading data part then could I achieve what I want?

like image 877
Arjunsinh Jadeja Avatar asked Mar 19 '23 10:03

Arjunsinh Jadeja


1 Answers

Add

File file = new File(FILENAME);
if(!file.exists())
{  
   file.createNewFile()
   // write code for saving data to the file
}

above

fis = openFileInput(FILENAME);

This will check if there exists a File for the given FILENAME and if it doesn't it will create a new one.

like image 60
Apoorv Avatar answered Mar 27 '23 14:03

Apoorv