Search code examples
android-studiofilesaveruntime-error

Android Studio: How to save to file


I am executing this code to save some data to a file in my android phone but when saving it the FileNotFoundException triggers and I dont know why since I copy from many different places but is not working for me.

Hints?

    public void safeToExcelFile(View view) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000);
    }
    if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
        String fileName = "hola" + ".txt";
        String contenido = "pues algo a ver si va";

        File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_NOTIFICATIONS);
        File dir = new File(root.getAbsolutePath()+"/MyAppFile");
        if(!dir.exists()) {
            dir.mkdir();
        }
        File file = new File(dir, fileName);

        Toast.makeText(this, dir.getPath(), Toast.LENGTH_LONG).show();

        try{
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(contenido.getBytes());
            fos.close();
            Toast.makeText(this, "Se guardo", Toast.LENGTH_LONG).show();
        } catch (FileNotFoundException e) {
            Toast.makeText(this, "Archivo no encontrado", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        } catch (IOException e) {
            Toast.makeText(this, "Error al guardar", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }else{
        Toast.makeText(this, "No puedes guardar", Toast.LENGTH_LONG).show();
    }

}

Solution

  • I finnaly figured out the answer, i got the solution from https://blog.cindypotvin.com/saving-data-to-a-file-in-your-android-application/ if you are interested

       try {
            File testFile = new File(this.getExternalFilesDir(null), "Cuentas.csv");
            if (!testFile.exists())
                testFile.createNewFile();
            Toast.makeText(this, testFile.getPath(), Toast.LENGTH_LONG).show();
    
            // Adds a line to the file
            BufferedWriter writer = new BufferedWriter(new FileWriter(testFile, true));
            writer.write("This is a test file.");
            writer.close();
            // Refresh the data so it can seen when the device is plugged in a
            // computer. You may have to unplug and replug the device to see the
            // latest changes. This is not necessary if the user should not modify
            // the files.
            MediaScannerConnection.scanFile(this,
                    new String[]{testFile.toString()},
                    null,
                    null);
        } catch (IOException e) {
            //Log.e("ReadWriteFile", "Unable to write to the TestFile.txt file.");
            Toast.makeText(this, "Error al guardar", Toast.LENGTH_LONG).show();
        }