How to create a txt in android sdk 22 lolipop that is accessible from file explorer

2

My program allows me to save and retrieve a document, but it is saved in a directory that can only be accessed if I have the phone rooted.

How do I store it in an accessible directory such as Documents?

I want to implement it for phones with SDK 22 (Lolipop 5.1) and onwards, I'm using Android Studio 3.0.1

This is the code for main_activity.java

function that defines if the document exists

private boolean existeFile(String[] archivos,String archivo)
{
    for(int f=0;f<archivos.length;f++)
        if(archivo.equals(archivos[f]))
            return true;
    return false;
}

function searching for the document

public void Buscar(View view)
{
    String[] archivos = fileList();
    String archivo = etArchivo.getText().toString();
    archivo = archivo.replace('/','-') + ".txt";

    //Código para recuperar el archivo de la MicroSD
    /*
    try{
        File tarjeta = Environment.getExternalStorageDirectory();
        File file = new File(tarjeta.getAbsolutePath(),archivo);
        if(file.exists()){
            FileInputStream fin = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(fin);
            BufferedReader br = new BufferedReader(isr);
            String linea = br.readLine();
            String texto = "";
            while (linea != null){
                texto = texto + linea + "\n";
                linea = br.readLine();
            }
            br.close();
            isr.close();
            etTexto.setText(texto);
        }else{
            Toast.makeText(this,"El archivo no existe",Toast.LENGTH_SHORT).show();
        }

    }catch(IOException e){
        Log.i("Agenda",e.toString());
    }*/

    //Código para recuperar el archivo de la memoria interna
    if(existeFile(archivos,archivo))
    {
        try
        {
            InputStreamReader file = new InputStreamReader(openFileInput(archivo));
            BufferedReader br = new BufferedReader(file);
            String linea = br.readLine();
            String texto = "";
            while(linea != null)
            {
                texto += linea + "\n";
                linea = br.readLine();
            }
            br.close();
            file.close();
            etTexto.setText(texto);
         }
         catch (IOException e)
        {
            Log.i("Agenda",e.toString());
        }
    }
    else
    {
        Toast.makeText(this,"El archivo no existe",Toast.LENGTH_SHORT).show();
    }
}

function that you write in the document

public void Grabar(View view)
{
    String archivo = etArchivo.getText().toString();
    archivo = archivo.replace('/','-') + ".txt";

    try
    {
        //Guardar en MicroSD
        /*File tarjeta = Environment.getExternalStorageDirectory();
        File file = new File(tarjeta.getAbsolutePath(),archivo);
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file));
        osw.write(etTexto.getText().toString());
        osw.flush();
        osw.close();*/
        OutputStreamWriter file = new OutputStreamWriter(openFileOutput(archivo,MODE_PRIVATE));
        file.write(etTexto.getText().toString());
        file.flush();
        file.close();
    }
    catch (IOException e){
        Log.i("Agenda",e.toString());
    }
    Toast.makeText(this,"Datos grabados",Toast.LENGTH_SHORT).show();
    this.LimpiarTextos();
}

This is my content of my manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.luisg.agenda">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Vista"></activity>
    </application>

</manifest>
    
asked by Kuroi 05.04.2018 в 16:47
source

1 answer

2

How to create a .txt file that is accessible from file browser

  

My program allows me to save and retrieve a document, but this one   saved in a directory that can only be accessed if I have the   Rooted phone.

Actually you should simply get the path of the external directory by:

Environment.getExternalStorageDirectory();

This way you can view it through the file browser without having to have "root" permissions.

Permission is also required within your AndroidManifest.xml :

  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

This is an example according to your code:

  public void Grabar(View view) {

        String archivo = etArchivo.getText().toString();
        archivo = archivo.replace('/','-') + ".txt";

        //Obtiene ruta de sdcard
        File pathToExternalStorage = Environment.getExternalStorageDirectory();
        //agrega directorio /myFiles
        File appDirectory = new File(pathToExternalStorage.getAbsolutePath() + "/myFiles/");
        //Si no existe la estructura, se crea usando mkdirs()
        appDirectory.mkdirs();
        //Crea archivo
        File saveFilePath = new File(appDirectory, archivo);

        try {
            FileOutputStream fos = new FileOutputStream(saveFilePath);
            OutputStreamWriter file = new OutputStreamWriter(fos);
            file.write(etTexto.getText().toString());
            file.flush();
            file.close();
        } catch (FileNotFoundException e) {
            Log.i("Agenda",e.toString());
        } catch (IOException e) {
            Log.i("Agenda",e.toString());
        }

        Toast.makeText(this,"Datos grabados",Toast.LENGTH_SHORT).show();
        this.LimpiarTextos();

    }

The file is created in external storage and can be viewed:

The method to read the contents of your file should also be modified to read the path where the file was initially created,

It is important to mention that the name of the file to be searched must be in the archivos array, otherwise it will not allow the contents of the file to be read,

 if(existeFile(archivos,archivo))
    {
     ...
     ...

the code to read the file would be:

   public void Buscar(View view)
    {
        String[] archivos = fileList();
        String archivo = etArchivo.getText().toString();
        archivo = archivo.replace('/','-') + ".txt";


        //Código para recuperar el archivo de la memoria interna
        if(existeFile(archivos,archivo))
        {
            try
            {
                //Obtiene ruta de sdcard
                File pathToExternalStorage = Environment.getExternalStorageDirectory();
                //agrega directorio /myFiles
                File appDirectory = new File(pathToExternalStorage.getAbsolutePath() + "/myFiles/");
                //Si no existe la estructura, se crea usando mkdirs()
                appDirectory.mkdirs();
                //Crea archivo
                File saveFilePath = new File(appDirectory, archivo);
                BufferedReader br = new BufferedReader(new FileReader(saveFilePath));
                String linea; // = br.readLine();
                String texto = "";
                while((linea  = br.readLine())!= null)
                {
                    texto += linea + "\n";
                }
                br.close();
                etTexto.setText(texto);
            }
            catch (IOException e)
            {
                Log.i("Agenda",e.toString());
            }
        }
        else
        {
            Toast.makeText(this,"El archivo no existe",Toast.LENGTH_SHORT).show();
        }
    }
    
answered by 05.04.2018 / 18:27
source