Android 尝试创建文件时返回空指针

Android 尝试创建文件时返回空指针,android,file,nullpointerexception,Android,File,Nullpointerexception,我有这段代码将浮点数组保存到一个文件中以备将来使用。但是当我用顺序saveArray(“x”,x)调用它时其中x是我要保存的浮点数组,它会将Null返回到文件,而不是创建的 public void saveArray(String filename, float[] array) { try { FileOutputStream fos = new FileOutputStream(filename); ObjectOutputS

我有这段代码将浮点数组保存到一个文件中以备将来使用。但是当我用顺序
saveArray(“x”,x)调用它时其中x是我要保存的浮点数组,它会将Null返回到文件,而不是创建的

public void saveArray(String filename, float[] array) {
         try {
            FileOutputStream fos = new FileOutputStream(filename);
            ObjectOutputStream out = new ObjectOutputStream(fos);
            out.writeObject(array);

            out.flush();
            out.close();
         }
         catch (IOException e) {
             System.out.println(e); 
         }
      }

     public float[] loadArray(String filename) {
          try {
            FileInputStream fis = new FileInputStream(filename);
            ObjectInputStream in = new ObjectInputStream(fis);
            float[] saved_array = (float[])in.readObject();
            in.close();
            return saved_array;
          }
          catch (Exception e) {
              System.out.println(e);
          }
          return null;
      }
这就是我试图保存时的回报

05-04 07:21:59.547: I/System.out(622): java.io.FileNotFoundException: /the x: open failed: EROFS (Read-only file system)
05-04 07:21:59.547: I/System.out(622): java.io.FileNotFoundException: /the x: open failed: ENOENT (No such file or directory)
05-04 07:21:59.557: I/System.out(622): null
我找到了解决办法,但我需要更多的帮助

我像以前一样离开了saveArray,并在前面创建了一个dir和一个文件

final File dir = new File(context.getFilesDir() + "/works");
dir.mkdirs(); 
final File file = new File(dir, "the_x.txt");
saveArray(file.getPath()+file.getName(),x);
而且似乎得救了。现在,我尝试将其加载到另一个数组中,但新数组“a”的值从未改变。你认为错在哪里?查看上面的loadArray函数。 我试试这些:

a = loadArray(file.getPath()+file.getName());
a = loadArray(file.getName());
a = loadArray(file.getPath());
a = loadArray("the_x.txt");

如果您正在sd卡中写入文件,则需要以下权限

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

是否在清单中添加了写入权限?不,我没有。需要吗?是的。你需要许可证你能发布你文件的路径吗?你是什么意思?我没有在任何其他位置创建它。我以前写的,是我用来做文件的,你是什么意思?我没有在任何其他位置创建它。我之前写的是我对文件的使用,我只想看到文件名字符串。。想知道您是否使用任何内部文件吗?它不允许我写“\sdcard\yourfile.txt”。可能是“/sdcard/yourfile.txt”?现在它会更改它,并显示权限消息05-04 08:11:50.267:I/System.out(949):java.io.FileNotFoundException:/sdcard/thex.txt:open failed:EACCES(权限被拒绝)I放入您为权限编写的内容如果我删除/sdcard,我会收到消息05-04 08:15:53.889:I/System.out(996):java.io.FileNotFoundException:/thex.txt:open失败:EROFS(只读文件系统)
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(
                context.openFileOutput(
                        filename, Context.MODE_PRIVATE));