简体   繁体   中英

File not found Excepiton while writing in Sdcard Android

This is my code

public class MainActivity extends Activity {
private String PRENOM = "prenom.txt";
private String userName = "Apollidore";
private File mFile = null;

private Button mWrite = null;
private Button mRead = null;
String state = Environment.getExternalStorageState();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);// On crée un fichier qui correspond à l'emplacement extérieur
mFile = new File(Environment.getExternalStorageDirectory().getPath()+ "/Android/data/ " +getPackageName()+ "/files/" + PRENOM);


mWrite = (Button) findViewById(R.id.write);
mWrite.setOnClickListener(new View.OnClickListener() {


  public void onClick(View pView) {
    try {
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            // We can read and write the media
            Log.v("state", "mounted");
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            Log.v("state", "read only");
        } else {
            // Something else is wrong. It may be one of many other states, but all we need
            //  to know is we can neither read nor write
            Log.v("state", "gg");
        }
      // Flux interne
      FileOutputStream output = openFileOutput(PRENOM, MODE_WORLD_WRITEABLE);

      // On écrit dans le flux interne
  //    output.write(userName.getBytes());

  /*    if(output != null)
        output.close();*/

      // Si le fichier est lisible et qu'on peut écrire dedans
      if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
          && !Environment.MEDIA_MOUNTED_READ_ONLY.equals(Environment.getExternalStorageState())) {
      Log.v("state" ,"enter");
        mFile.createNewFile(); if ( mFile.createNewFile())Log.v("file", "created");
        output = new FileOutputStream(mFile);
        output.write(userName.getBytes());
        if(output != null)
          output.close();
      }
      else {
          Toast.makeText(MainActivity.this, Environment.getExternalStorageState(), Toast.LENGTH_SHORT).show();

      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
});

mRead = (Button) findViewById(R.id.read);
mRead.setOnClickListener(new View.OnClickListener() {

  public void onClick(View pView) {
    try {
      FileInputStream input = openFileInput(PRENOM);
     int value;
      // On utilise un StringBuffer pour construire la chaîne au fur et à mesure
      StringBuffer lu = new StringBuffer();
      // On lit les caractères les uns après les autres
      while((value = input.read()) != -1) {
        // On écrit dans le fichier le caractère lu
        lu.append((char)value);
      }
  //  Toast.makeText(MainActivity.this, "Interne : " + lu.toString(), Toast.LENGTH_SHORT).show();
      if(input != null)
        input.close();

      if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {

           Log.v("state" ,"enter");
        lu = new StringBuffer();
        input = new FileInputStream(mFile);
        while((value = input.read()) != -1)
        lu.append((char)value);
        Toast.makeText(MainActivity.this, "Externe : " + lu.toString(),     Toast.LENGTH_SHORT).show();
        if(input != null)
          input.close();
      }
      else
      {
          Toast.makeText(MainActivity.this, Environment.getExternalStorageState(), Toast.LENGTH_SHORT).show();

      }

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
});
 }
 }

Log file :

   06-16 11:15:36.380: V/state(5335): mounted
   06-16 11:15:36.380: V/state(5335): enter
   06-16 11:15:36.380: W/System.err(5335): java.io.IOException: No such file or directory
   06-16 11:15:36.380: W/System.err(5335):  at java.io.File.createNewFileImpl(Native Method)
   06-16 11:15:36.380: W/System.err(5335):  at  java.io.File.createNewFile(File.java:1257)
   06-16 11:15:36.380: W/System.err(5335):  at com.example.testprediction.MainActivity$1.onClick(MainActivity.java:63)
   06-16 11:15:36.380: W/System.err(5335):  at android.view.View.performClick(View.java:2506)
   06-16 11:15:36.380: W/System.err(5335):  at android.view.View$PerformClick.run(View.java:9112)
   06-16 11:15:36.380: W/System.err(5335):  at android.os.Handler.handleCallback(Handler.java:587)
   06-16 11:15:36.380: W/System.err(5335):  at android.os.Handler.dispatchMessage(Handler.java:92)
   06-16 11:15:36.380: W/System.err(5335):  at android.os.Looper.loop(Looper.java:130)
   06-16 11:15:36.380: W/System.err(5335):  at android.app.ActivityThread.main(ActivityThread.java:3835)
   06-16 11:15:36.390: W/System.err(5335):  at java.lang.reflect.Method.invokeNative(Native Method)
   06-16 11:15:36.390: W/System.err(5335):  at java.lang.reflect.Method.invoke(Method.java:507)
   06-16 11:15:36.390: W/System.err(5335):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
   06-16 11:15:36.390: W/System.err(5335):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
   06-16 11:15:36.390: W/System.err(5335):  at dalvik.system.NativeStart.main(Native Method)

   06-16 11:15:45.420: V/state(5335): mounted
   06-16 11:15:45.430: V/state(5335): enter
   06-16 11:15:45.430: W/System.err(5335): java.io.IOException: No such file or directory
   06-16 11:15:45.430: W/System.err(5335):  at java.io.File.createNewFileImpl(Native Method)
   06-16 11:15:45.430: W/System.err(5335):  at java.io.File.createNewFile(File.java:1257)
   06-16 11:15:45.430: W/System.err(5335):  at com.example.testprediction.MainActivity$1.onClick(MainActivity.java:63)
   06-16 11:15:45.430: W/System.err(5335):  at android.view.View.performClick(View.java:2506)
   06-16 11:15:45.430: W/System.err(5335):  at android.view.View$PerformClick.run(View.java:9112)
   06-16 11:15:45.430: W/System.err(5335):  at android.os.Handler.handleCallback(Handler.java:587)
   06-16 11:15:45.430: W/System.err(5335):  at android.os.Handler.dispatchMessage(Handler.java:92)
   06-16 11:15:45.430: W/System.err(5335):  at android.os.Looper.loop(Looper.java:130)
   06-16 11:15:45.430: W/System.err(5335):  at android.app.ActivityThread.main(ActivityThread.java:3835)
   06-16 11:15:45.430: W/System.err(5335):  at java.lang.reflect.Method.invokeNative(Native Method)
   06-16 11:15:45.430: W/System.err(5335):  at java.lang.reflect.Method.invoke(Method.java:507)
   06-16 11:15:45.440: W/System.err(5335):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
   06-16 11:15:45.440: W/System.err(5335):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)

Edit

a changed the declaration of mFile to

     mFile=new File(getApplicationContext().getExternalFilesDir(null).getName()+PRENOM) 

and I added those lines which through a NullPointer Exception

   if(!mFile.getParentFile().exists())
      {
          mFile.getAbsoluteFile().mkdirs();
      }

Before calling createNewFile get the parent file of yours file and call mkdirs() method from it.

And also use context.getExternalFilesDir() or context.getExternalCacheDir() . It seems like you're trying to save data to one of this directories and this is more correct way to get path to them.

Have you given read/write sdcard permissions in your AndroidManifest.xml?

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

What @Livingston says is true. Another thing is there:

mFile.createNewFile(); 
if ( mFile.createNewFile()) <-- ALWAYS RETURNS FALSE

Remove the first call. With your current code you will not even know whether you have actually succeeded in creating the file to begin with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM