4

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?

3 Answers3

9

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.

Apoorv
  • 13,470
  • 4
  • 27
  • 33
  • Looks promising, let me give it a shot. – Arjunsinh Jadeja Jun 04 '14 at 05:42
  • This is most certainly what you're looking for. – arielnmz Jun 04 '14 at 06:06
  • Yes! Finally it gets the job done although it wasn't as simple as it appeared. I had to change a things or two. First thing was to cut the whole saving data part and paste it into a new function that I named "createfileinstantly" (You could probably give that a better name :p) and then under the IF condition replace "file.createNewFile()" with "createfileinstantly();" And then it works perfectly! So please edit your answer to reflect the following things so that anyone with the same issue would get a very direct fix. Thank you! – Arjunsinh Jadeja Jun 04 '14 at 06:08
0

If you're working on Android, why don't you use the API's solution for saving files?

Quoting:

String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;

try {
  outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
  outputStream.write(string.getBytes());
  outputStream.close();
} catch (Exception e) {
  e.printStackTrace();
}

You should really read the whole document, they explain pretty well the basic ways of creating or accessing files, you can also check the different ways of storing data.

But regarding your original question:

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?

Yes, you could achieve it.

arielnmz
  • 8,354
  • 9
  • 38
  • 66
  • Turns out adding the save data code in the "FileNotFoundException" crashes the app. – Arjunsinh Jadeja Jun 04 '14 at 06:00
  • Of course the solution is not just to copy/paste code, the idea of the catch block is to just know if the file was not found and create it. As I said, if you're developing for an Android device I suggest you stick to the API's tools and guidelines. Or if it's only java-related I think the best (and simplest) solution would be Apoorv's answer. – arielnmz Jun 04 '14 at 06:05
0

Try this one:

public static void readData() throws IOException
{
    File file = new File(path, filename);
    if (!file.isFile() && !file.createNewFile()){
        throw new IOException("Error creating new file: " + file.getAbsolutePath());
    }

    BufferedReader r = new BufferedReader(new FileReader(file));
    try {
        // ...
        // read data
        // ...
    }finally{
        r.close();
    }
}

Ref: Java read a file, if it doesn't exist create it

Community
  • 1
  • 1
Pratik Butani
  • 60,504
  • 58
  • 273
  • 437