在Sdcard Android中编写时未找到文件异常

时间:2013-06-16 10:17:58

标签: java android file sd-card

这是我的代码

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();
    }
  }
});
 }
 }

日志文件:

   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)

修改

mFile的声明更改为

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

我添加了那些通过NullPointer Exception

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

3 个答案:

答案 0 :(得分:1)

在调用createNewFile之前获取您的文件的父文件并从中调用mkdirs()方法。

并使用context.getExternalFilesDir()context.getExternalCacheDir()。看起来您正在尝试将数据保存到其中一个目录中,这是获取路径的更正确方法。

答案 1 :(得分:0)

您是否在AndroidManifest.xml中获得了读/写SD卡权限?

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

答案 2 :(得分:0)

@Livingston说的是真的。另一件事是:

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

删除第一个电话。使用您当前的代码,您甚至不知道您是否真的成功地创建了文件。