我正在尝试将文件写入手机(以及将来用户的手机)上的内部设备存储。我正在观看 2016 年的视频教程 ( https://www.youtube.com/watch?v=EhBBWVydcH8 ),其中展示了他如何非常简单地将输出写入文件。如果您想查看他的代码,请跳至 8:23。
无论如何,我基本上尝试了他的代码,然后由于那不起作用,我想会四处搜索。
显然,要创建文件,我需要以下代码行:
String filename = "textfile.txt";
File file = new File(filename);
file.mkdirs();
file.createNewFile();
在第二行 file.createNewFile() 上,我收到以下错误:
java.io.IOException: Read-only file system
at java.io.UnixFileSystem.createFileExclusivel
at java.io.UnixFileSystem.createFileExclusivel
at java.io.File.createNewFile(File.java:948)
etc......
然后,如果我仅使用教程中的代码行运行代码,我会得到一个空指针。
代码:
try {
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(IDNum.getBytes());
fos.close();
System.out.println("Wrote STuff Outputtt?");
} catch (Exception e) {
e.printStackTrace();
}
错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.FileOutputStream android.content.Context.openFileOutput(java.lang.String, int)' on a null object reference
at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:199)
at com.lecconnect.lockoutdemo.FileManager.AddUser(FileManager.java:37)
第 37 行是 try/catch 中的第一行。
如果您需要任何其他信息来帮助我,请告诉我。非常感谢您的回复。
最佳答案
将目录和文件本身分开很重要。
在您的代码中,您对要写入的文件调用 mkdir
s,这是不正确的用法,因为 mkdirs
将您的文件放入目录中。您应该仅对目录调用 mkdirs,因此如果目录不存在,则会创建该目录,并且当您为此创建新的 FileOutputStream 对象时,将自动创建该文件文件。
试试这个:
File directory = getFilesDir(); //or getExternalFilesDir(null); for external storage
File file = new File(directory, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(IDNum.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
关于java - Android Studio - 只读文件系统?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44339963/