0

I am using android studio just to see how to create a file, or if a file already exists use the existing file. My code so far is:

              public void saveFile(){

            try{

            FileOutputStream fOut = openFileOutput("current.xml", 
            Context.MODE_APPEND);
            //OutputStreamWriter outputWriter = new 
             OutputStreamWriter(fOut);

            XmlSerializer serializer = Xml.newSerializer();
            serializer.setOutput(fOut, "UTF-8");
            serializer.startDocument(null, Boolean.valueOf(true));

            serializer.startTag(null, "records");
            serializer.startTag(null,"employee");
            serializer.startTag(null, "name");
            serializer.text("Ryan");
            serializer.endTag(null,"name");
            serializer.startTag(null,"surname");
            serializer.text("Derk");
            serializer.endTag(null,"surname");
            serializer.startTag(null,"salary");
            serializer.text("60000");
            serializer.endTag(null,"salary");
            serializer.endTag(null,"employee");
            serializer.endTag(null,"records");

            serializer.endDocument();
            serializer.flush();
            fOut.close();

            Toast.makeText(getApplicationContext(), "Save Successful", 
            Toast.LENGTH_LONG).show();

            }
            catch(Throwable t){

            Toast.makeText(getApplicationContext(), "Save Unsuccessful", 
            Toast.LENGTH_LONG).show();

        }


        }

         private static String getValue(String tag, Element element) {
         NodeList nodeList = 
         element.getElementsByTagName(tag).item(0).getChildNodes();
         Node node = nodeList.item(0);
         return node.getNodeValue();
        }

How can i check if the file is already created before saving to that file? And if it is not created create the file?

RW6
  • 59
  • 1
  • 14
  • 1
    Duplicate ?https://stackoverflow.com/questions/1816673/how-do-i-check-if-a-file-exists-in-java – Jens Jun 01 '17 at 14:28
  • 1
    Possible duplicate of [How do I check if a file exists in Java?](https://stackoverflow.com/questions/1816673/how-do-i-check-if-a-file-exists-in-java) – LazerBanana Jun 01 '17 at 14:30
  • @InjuredThePatient I actually looked into both of those links and I couldn't for the life of me actually create a working prototype. If there are any suggestions I will definitely appreciate it. – RW6 Jun 01 '17 at 14:36
  • simply - if(!yourfile.existst()){doYourStuff} then if the file is not there is going to do all your code if it exists is not going to bother. Depends if you want to overwrite it or not. – LazerBanana Jun 01 '17 at 14:39
  • On the first run of the app, I want the specific data to be saved on the file. And i tried to do if(!yourfile.exists()) but it still executes the if statement every time i press the button to save. – RW6 Jun 01 '17 at 14:43
  • If im not mistaking, openFileoutout creates the file if it does not exsits( https://developer.android.com/reference/android/content/Context.html#openFileOutput(java.lang.String, int)) See the link from InjuredThePatient.. – user1086500 Jun 01 '17 at 14:44
  • can you share the code of openFileOutput ? – Firerazzer Jun 01 '17 at 14:45
  • Im pritty sure I have, that's everything I have to create and save the file. – RW6 Jun 01 '17 at 14:48
  • @Firerazzer here is the project folder: https://Rwinger0320@bitbucket.org/Rwinger0320/filein_fileout.git – RW6 Jun 01 '17 at 14:57

4 Answers4

1

If I correctly understand your problem:

  • You need to have your application Context android.content.Context to call the method openFileOutput.

  • Also, to check if the file exists, you can call Context.fileList() to get the list of files in the context and check if your files exist.

    String[] files = fileList();
    for (String file : files) {
        if (file.equals(myFileName)) {
            //file exits
        }
    
Pang
  • 9,564
  • 146
  • 81
  • 122
Haythem ROUIS
  • 347
  • 2
  • 10
  • That is correct, I call the write file method which creates the files and then writes to it. But I want to then if the method is called a second time it to check if the file has been already created and if so to execute and else statement. This is going to be for when the user closes the app and reopens the app, the file will have already been created so we don't want the file to be created again. How would I be able to do this, I have tried to implement the if(!filename.exists) but when it is created it still executes the if statement. – RW6 Jun 01 '17 at 17:38
  • can you try this code : `File file = new File(path); if (!file.isFile()) { // file does not exist }else{ // file do exist }` – Haythem ROUIS Jun 02 '17 at 07:49
0

Simply use yourFile.exists();.

Firerazzer
  • 192
  • 1
  • 13
  • I tried doing that and instead it kept going into the if statement. I put an if statement with the argument if(!yourFile.exists) but after the first time it ran, i pressed my button again and it ran a second and third time. Causing "processing instructions must not start with xml" when i tried to load it – RW6 Jun 01 '17 at 14:33
  • I am trying to write now within the try statement. I have if(!fOut.exists) but i am getting a cannot resolve symbol from it. Any suggestions – RW6 Jun 01 '17 at 14:40
  • Basically the save button is acting as the first load of the app and then if you press it again instead of it re-writing the same info it will execute the else statement if there is already a file created. – RW6 Jun 01 '17 at 15:04
0

You need to point to the file and check if it exists.

 File file = new File("C:\\file.txt");

    if(!file.exists()){
        System.out.println("file does not exist");
        //Do all your stuff here
    }
LazerBanana
  • 6,865
  • 3
  • 28
  • 47
  • Since Im adding the xml file to the internal storage I dont know here the file gets stored in the directory. I already looked on androids site but i couldn't find where the actually file is located. So when declaring File file = new file I dont know what to specify for the argument. – RW6 Jun 01 '17 at 14:50
  • i see, can you give a bit more code to see what you are doing? and what is `openFileOutput` doing ? – LazerBanana Jun 01 '17 at 14:59
  • Feel free to download it at: https://Rwinger0320@bitbucket.org/Rwinger0320/filein_fileout.git - it is a public prject – RW6 Jun 01 '17 at 14:59
0

For my case what i had done is added this method:

       public Boolean checkFile(){

    Boolean myBool2 = false;
    File file  = getBaseContext().getFileStreamPath("current.xml");

    if(file.exists()){

        Toast.makeText(getApplicationContext(), "FileFound", 
    Toast.LENGTH_LONG).show();

    }

    else{

        Toast.makeText(getApplicationContext(), "No file found", 
    Toast.LENGTH_LONG).show();
        myBool2 = true;
    }
        return myBool2;

}

And it turns out that it worked! I just needed to get the context and then the filestreampath and it found the file.Thanks for everyone who has posted on this question, it really helped me understand what I was really trying to do!

RW6
  • 59
  • 1
  • 14