#1
  1. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2005
    Posts
    296
    Rep Power
    15

    Check, create and read from file in internal storage


    Hi,

    I am trying to get my android app to do the following:

    1. Check to see if a file exists within the application folder on internal storage (NOT SD! NOT EXTERNAL!).

    2. If the file does not exist, create it by copying the file from resources folder into the application folder.

    3. Read the new file.

    The following code will check and create the file if necessary. FileData is just a basic structure for holding the name and byte array data.

    Code:
    final static String VERSION_FILE = "content.xml";
    
    File versionFile = new File(VERSION_FILE);
    
    if (!versionFile.exists()) {
    new CreateFile().execute(new FileData(VERSION_FILE, getResources().getXml(R.xml.content).toString().getBytes()));
    }
    
    private class CreateFile extends AsyncTask<FileData, Integer, Boolean> {
    		@Override
    		protected Boolean doInBackground(FileData... fd) {
    			FileOutputStream fos = null;
    			
    			try {
    				fos = openFileOutput(fd[0].getFilename(), Context.MODE_PRIVATE);
    				fos.write(fd[0].getData());				
    				return true;
    			} catch (FileNotFoundException e) {
    				e.printStackTrace();
    			} catch (NotFoundException e) {
    				e.printStackTrace();
    			} catch (IOException e) {
    				e.printStackTrace();
    			} finally {
    				try {
    					fos.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    			
    			return false;
    		}
    	}
    I then create an input stream for an XML parser to handle by doing the following and passing it to an input source:

    Code:
    InputStream is;
    File f = new File(VERSION_FILE);
    is = new FileInputStream(f);
    However once this reaches the parser an exception is thrown to say the file does not exist.

    I cannot see what I am doing wrong since the documentation on the android site and pretty much every google search I have made suggests that the file should be created or overwritten by my first few lines of code.
  2. #2
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2012
    Posts
    3
    Rep Power
    0
    i think its because you didn't specify where the file should be written. or the current location it is currently writing in doesn't have a write permission.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2012
    Posts
    16
    Rep Power
    0
    i think its because you didn't specify where the file should be written

IMN logo majestic logo threadwatch logo seochat tools logo