How can I validate if a file exists or not?

1

I have a problem when doing a validation to see if a file exists or not, the problem is that in the validation it always shows me that the file does not exist, when I close the application or change of activity and return to my activity where I have the validation re-creates the blank file

This is the code that I implemented to validate:

File fs = new File(FILE_NAME);

if(fs.exists()){
    Toast.makeText(this,"El archivo ya esta cargado", Toast.LENGTH_SHORT).show();
}else{
    try {
        Toast.makeText(this,"El archivo no se ha generado", Toast.LENGTH_SHORT).show();
        FileOutputStream fos = this.openFileOutput(FILE_NAME, Activity.MODE_PRIVATE);
        fos.write(notas.getBytes());
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

I do not know why it does not enter the first validation, the file I'm sure is created because it does not show me an error when saving some record, but when entering the if it always shows that the file does not exist.

This is the complete class where I have the validation:

package com.example.enriq.myapplication;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.example.enriq.myapplication.adapter.NotaAdapter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class Principal extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
    private String archivo = "sesion.obj";
    private RecyclerView notasRecyclerView;
    private static final String FILE_NAME = "notas.txt";
    private NotaAdapter adapter;
    private String notas="";
    private ServicioArchivo servicio = new ServicioArchivo(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_principal);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        File fs = new File(FILE_NAME);

        if(fs.exists()){
            Toast.makeText(this,"El archivo ya esta cargado", Toast.LENGTH_SHORT).show();
        }else{
            try {
                Toast.makeText(this,"El archivo no se ha generado", Toast.LENGTH_SHORT).show();
                FileOutputStream fos = this.openFileOutput(FILE_NAME, Activity.MODE_PRIVATE);
                fos.write(notas.getBytes());
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
/*
        notasRecyclerView = (RecyclerView) findViewById(R.id.rv_notas);
        try {
            adapter = new NotaAdapter(this, Arrays.asList(servicio.leerNotas()));
        } catch (IOException e) {
            Toast.makeText(Principal.this, "No existe un archivo aún", Toast.LENGTH_SHORT).show();
            adapter = new NotaAdapter(this, new ArrayList<String>());
            //servicio = new ServicioArchivo(this, servicio.cargar());
        }

        notasRecyclerView.setHasFixedSize(true);
        notasRecyclerView.setAdapter(adapter);
        notasRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));

*/

        View header = navigationView.getHeaderView(0);
        TextView text = (TextView) header.findViewById(R.id.ususesion);
            try {
                ObjectInputStream objInput = new ObjectInputStream(openFileInput(archivo));
                Usuario persona = (Usuario) objInput.readObject();
                objInput.close();
                text.setText(persona.toString());
                Toast.makeText(this, "Sesión inicia con exito", Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                Toast.makeText(this, "Error al cargar el archivo", Toast.LENGTH_SHORT).show();
            } catch (ClassNotFoundException e) {
                Log.e("MainActivity", "Error clase no encontrada");
            }
    }

    @Override
    public void onBackPressed(){
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if(drawer.isDrawerOpen(GravityCompat.START)){
            drawer.closeDrawer(GravityCompat.START);
        }else{
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


    public boolean onOptionsItemSelected(MenuItem item){
        //este metodo es para obtener el id del menu de los
        //tres puntos
        int id = item.getItemId();

        if(id == R.id.exportar){
            //onClickRadio(view);
        }else if(id == R.id.sesion){
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();

        if(id == R.id.iniciotap){
            /*Parqueos parqueos = new Parqueos();
            android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
            manager.beginTransaction().replace(R.id.exp, parqueos).commit();*/
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            toolbar.setSubtitle("Parqueos");

        }else if(id == R.id.noticiastap){
            //Traemos al fragmento de noticias
            /*configuracion confi = new configuracion();
            android.support.v4.app.FragmentManager manager = getSupportFragmentManager();
            //vamos a sustitur el contenedor del activity main por un nuevo fragment
            manager.beginTransaction().replace(R.id.exp, confi).commit();*/
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            toolbar.setSubtitle("Preferencias");


           getFragmentManager().beginTransaction()
                    .replace(android.R.id.content, new ConfiguracionesFragment())
                    .commit();

        }
        //Este codigo nos permite mostrar que menu esta seleccionado
        //para poder identificar que menu esta en uso
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
    public void onClickAlerta(View view){

        Dialogo dialogo = new Dialogo();
        dialogo.show(getSupportFragmentManager(), "confirmación");

    }

    public void actualizar(){
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        View header = navigationView.getHeaderView(0);
        TextView text = (TextView) header.findViewById(R.id.ususesion);
        final SharedPreferences mSharedPreference = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        String value=(mSharedPreference.getString("opcion1", "Joder tio"));
        Toast.makeText(this,"Estas en el metodo de actualizar",Toast.LENGTH_SHORT).show();
        text.setText(value.toString());
    }

}
    
asked by Kike hatake 12.03.2018 в 18:33
source

2 answers

2

First ensure that you have defined the permission:

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

for devices older than OS 6.0 you must request them manually:

Android Android 6.0 or later permission WRITE_EXTERNAL_STORAGE (which is also implicitly READ_EXTERNAL_STORAGE should be required manually, call this method:

private void checkExternalStoragePermission() {
    int permissionCheck = ContextCompat.checkSelfPermission(
            this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        Log.i("Mensaje", "No se tiene permiso para leer.");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 225);
    } else {
        Log.i("Mensaje", "Se tiene permiso para leer!");
    }
}

You can validate calling the method only operating systems greater than or equal to Android 6.0:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
    //Verifica permisos para Android 6.0+
     checkExternalStoragePermission();
}

If you try to create a file the way you do it, you will try to create it in a system location that is read only, therefore it will not be possible to do :

private static final String FILE_NAME = "notas.txt";
...
File fs = new File(FILE_NAME);

Change the path where the file will be written, for example in internal storage:

File fs = new File(getFilesDir() + "/" + FILE_NAME);
    
answered by 12.03.2018 / 18:53
source
0

Do this: File file = new File (context.getFilesDir (), filename) instead: File fs = new File (FILE_NAME);

O

File fs = new File (getApplicationContext (). getFilesDir () + "/" + FILE_NAME);

    
answered by 12.03.2018 в 18:52