1

这是我的代码

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)

编辑

a 将声明更改mFile

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

我通过 NullPointer Exception 添加了那些行

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

3 回答 3

1

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

并且还使用context.getExternalFilesDir()or context.getExternalCacheDir()。似乎您正在尝试将数据保存到此目录之一,这是获取它们的路径的更正确方法。

于 2013-06-16T10:25:22.883 回答
0

您是否在 AndroidManifest.xml 中授予了读/写 sdcard 权限?

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
于 2013-06-16T10:26:36.910 回答
0

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

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

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

于 2013-06-16T10:29:35.427 回答