How to open files with FileInputStream?

0

I have a problem, I am programming an app to encrypt files and I get the following error:

  

java.lang.RuntimeException: java.io.FileNotFoundException:   /tmp/File.txt: open failed: ENOENT (No such file or directory)

This is my code:

public void encriptar(String clave)throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {

    //Archivo de entrada
    FileInputStream Entrada = new FileInputStream("/tmp/Archivo.txt");

    //Archivo de salida, encriptado
    FileOutputStream Salida = new FileOutputStream("/tmp/salida.txt");

    // ¡Cuidado al tomar la entrada del usuario! Https://stackoverflow.com/a/3452620/1188357

    //Tamaño de el arhivo  16 bytes

    SecretKey sks = new SecretKeySpec(clave.getBytes(),"AES");

    //Se crea el cipher, se encargan de encriptar los byte

    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE,sks);

    //stream de salida
    CipherOutputStream cos = new CipherOutputStream(Salida,cipher);

    //escribe bytes

    byte[] d = new byte[8];
    int b = Entrada.read(d);

    while(b != -1){

        cos.write(d,0,b);

        b = Entrada.read(d);
    }

    //cierra streams
    cos.flush();
    cos.close();
    Entrada.close();

}

and I call him from the OnCreate method of the main:

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

    final ArrayList<File> Archivos = EncontrarArchivos(Environment.getExternalStorageDirectory());

    Button BotonEncriptar = (Button) findViewById(R.id.boton1);
    Button BotonDesencriptar = (Button) findViewById(R.id.boton2);
    final EditText EntradaClave = (EditText) findViewById(R.id.clavesita);

    BotonDesencriptar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String clave = EntradaClave.getText().toString();

            try {
                desencriptar(clave);

            } catch (IOException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException k ) {
                throw new RuntimeException(k );
            }
        }
    });

             BotonEncriptar.setOnClickListener(new View.OnClickListener() {
                 @Override
                 public void onClick(View view) {

                    String clave = EntradaClave.getText().toString();

                     try {

                         encriptar(clave);

                     } catch (IOException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException k ) {
                         throw new RuntimeException(k );

                     }

                 }
             });
}

but I get the following error:

07-16 01:01:25.562 19145-19145/en1gm4app.user.pruebaencryptararchivos E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                    Process: en1gm4app.user.pruebaencryptararchivos, PID: 19145
                                                                                    java.lang.RuntimeException: java.io.FileNotFoundException: /tmp/Archivo.txt: open failed: ENOENT (No such file or directory)
                                                                                        at en1gm4app.user.pruebaencryptararchivos.MainActivity$2.onClick(MainActivity.java:73)
                                                                                        at android.view.View.performClick(View.java:5201)
                                                                                        at android.view.View$PerformClick.run(View.java:21215)
                                                                                        at android.os.Handler.handleCallback(Handler.java:739)
                                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                        at android.os.Looper.loop(Looper.java:148)
                                                                                        at android.app.ActivityThread.main(ActivityThread.java:5525)
                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
    
asked by MiguelCode 16.07.2017 в 08:16
source

2 answers

2

It means that the file does not exist or you do not have permission to read it (or the directory that contains it).

In the code you have as path "/tmp/Archivo.txt" and it is safest that you do not have permissions to read in that route. Try "/sdcard/Archivo.txt" or "/sdcard/tmp/Archivo.txt"

A couple of tips:

  • Use the class java.io.File and its methods to work with files.
  • Before opening a FileOutputStream to an arhivo, you should check that the parent directory exists. FileOutputStream can create the file if it does not exist but not the parent directory. Use File.mkdirs() always before instantiating 'FileOutputStream'

You must also request the permissions in the manifest:

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

As of Android 6, you should also request read, write, and run-time permissions.

Request permissions at runtime

    
answered by 16.07.2017 в 14:48
1

It is very possible that the path to the file is not correct.

Check the path where the file is located and access it:

File fileEntrada = new File(getActivity().getFilesDir(), "Archivo.xml");

It can also be a problem of lack of permissions, you should have in the manifest:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
answered by 16.07.2017 в 10:55