2017-04-10 6 views
1

J'ai une application Android où je permets à l'utilisateur de choisir un fichier du système de fichiers, je reçois ensuite le chemin et définir le chemin un EditText, puis utilisez ce chemin pour ouvrir le contenu du fichier.Obtenir un fichier à partir de l'appareil sur android, continue à indiquer le fichier introuvable lors de l'utilisation

Voici comment je suis le chargement du sélecteur de fichiers

Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
intent.setType("*/*"); 
intent.addCategory(Intent.CATEGORY_OPENABLE); 
intent.setAction(Intent.ACTION_GET_CONTENT); 
startActivityForResult(Intent.createChooser(intent, "Select your private key"), PRIVATE_KEY_PICKER); 

Ci-dessous mon onActivityResult

 protected void onActivityResult(int requestCode, int resultCode, Intent data) 
      { 
       switch (requestCode) 
       { 
        case PRIVATE_KEY_PICKER: 
         if (resultCode == Activity.RESULT_OK) 
         { 
          Uri uri = data.getData(); 

          String path = uri.getPath(); 

          txtPublicKeyPath.setText(path); 
         } 
         break; 
       } 
      } 

    The path that I get back and set to the EditText is: 

    `/document/primary:Download/my_file.txt` (my_file.txt being the file that was selected in the file picker). 

    To use the file I do the following: 

    File file = new File(txtPublicKeyPath.getText().toString()); 
       FileInputStream fis = new FileInputStream(file); 

       BufferedReader reader = new BufferedReader(new InputStreamReader(fis)); 
       StringBuilder sb = new StringBuilder(); 
       String line = null; 
       while ((line = reader.readLine()) != null) 
       { 
        sb.append(line + "\n"); 
       } 

       Intent intent = new Intent(); 
       intent.putExtra(PUBLIC_KEY_FILE, sb.toString()); 

       //If the certiticate passphrease has been provided, add this to the bundle 
       if (txtPassphrase.getText().length() > 0) 
       { 
        intent.putExtra(PUBLIC_KEY_PASSPHRASE, txtPassphrase.getText().toString()); 
       } 

       setResult(Activity.RESULT_OK, intent); 
       finish(); 
} 

Le code ci-dessus provoque l'exception suivante:

04-10 21:46:58.680 28866-28866/com.BoardiesITSolutions.MysqlManager E/SSHKeyManager: java.io.FileNotFoundException: /document/primary:Download/id_rsa (No such file or directory) 

Merci pour toute aide vous pouvez fournir.

Répondre

2

Pour utiliser le fichier que je fais ce qui suit:

getPath() n'a de sens que sur un Uri si le régime est file. Votre schéma est content.

Remplacer:

  File file = new File(txtPublicKeyPath.getText().toString()); 
      FileInputStream fis = new FileInputStream(file); 

avec:

  InputStream fis = getContentResolver().openInputStream(uri); 

En prime, le remplacement fonctionne pour les deux régimes file et content.

+0

Merci, jamais vu de cette façon, toujours vu le FileInputStream et le fichier en cours d'utilisation. Merci de votre aide – Boardy