Crashes while writing a file into internal storage


Last Updated:

  1. Zpecter

    Zpecter New Member

    Hello, I am developing an application and I have a problem when I try to save a file into the internal storage.

    The file is an xml and it's on the res/raw folder on my project. When the application starts, it checks if the file exists or not. If it doesn't exist, it copies the file from the res/raw folder into the internal storage, else it retrieves a field inside the file to check its version and if it's a newer version, it deletes the previous file and copies it again.

    Well, the problem is that if I have a new version and I have deleted the previous one, when I'm going to copy it again, it throws an NullPointerExceptcion and I can't find the problem, but I'm using the same code for both situations and I don't know how to solve it.

    This is the code I'm using:

    [HIGH]private void writeFileToInternalStorage() {
    InputStream fXmlFile = getResources().openRawResource(R.raw.xmlFile);
    FileOutputStream fos = null;
    try {
    File dir = getFilesDir();
    File file = new File(dir, "file.xml");
    if(file.exists()) {
    String versionRecursos = getFileVersion(fXmlFile);
    String versionLocal = getFileVersion(new FileInputStream(file));
    if (!versionRecursos.equalsIgnoreCase(versionLocal)) {
    file.delete();
    fos = openFileOutput("file.xml", Context.MODE_PRIVATE);
    copyFile(fos, fXmlFile);
    }
    }
    else {
    fos = openFileOutput("file.xml", Context.MODE_PRIVATE);
    copyFile(fos, fXmlFile);
    }
    }
    catch(IOException e) {
    e.printStackTrace();
    }
    catch (Exception e) {
    e.printStackTrace();
    }
    finally {
    if (fos != null) {
    try {
    fos.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    }

    protected void copyFile(OutputStream fos, InputStream fXmlFile) throws IOException {
    byte[] buffer = new byte[1024];
    int bytesRead = 0;
    while((bytesRead = fXmlFile.read(buffer)) > 0){
    fos.write(buffer, 0, bytesRead);
    }
    }[/HIGH]Any tips for solving it?? :mad:

    PS: The exception is thrown on this statement:

    [HIGH]while((bytesRead = fXmlFile.read(buffer)) > 0)[/HIGH]

    Advertisement

Share This Page