Java 当我尝试在Android中创建文件时,程序抛出异常
我正在尝试打开一个文件,如果它不存在,则创建它。我的代码抛出一个异常,表示文件不存在,但我认为使用rw选项,它会创建它Java 当我尝试在Android中创建文件时,程序抛出异常,java,android,file,Java,Android,File,我正在尝试打开一个文件,如果它不存在,则创建它。我的代码抛出一个异常,表示文件不存在,但我认为使用rw选项,它会创建它 // save dATA try { RandomAccessFile f=new RandomAccessFile("ted.dat", "rw"); f.write(cGlobals.mBoard[0], 0, cGlobals.fBoardSize* cGlobals.fBoardAmount); f.close(); } catch (F
// save dATA
try {
RandomAccessFile f=new RandomAccessFile("ted.dat", "rw");
f.write(cGlobals.mBoard[0], 0, cGlobals.fBoardSize* cGlobals.fBoardAmount);
f.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
是的,你想做的应该是有效的。但你到底在哪里写?尝试写入SD卡,将路径更改为
“/sdcard//ted.dat”
另外,我认为您应该具有以下内容:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
很抱歉,但我认为它不应该工作。虽然Android的javadoc没有提到这一点,但我在J2SE的javadoc中看到了这一点:
* @exception FileNotFoundException
* if the mode is <tt>"r"</tt> but the given string does not
* denote an existing regular file, or if the mode begins with
* <tt>"rw"</tt> but the given string does not denote an
* existing, writable regular file and a new regular file of
* that name cannot be created, or if some other error occurs
* while opening or creating the file
*@exception FileNotFoundException
*如果模式为“r”,但给定的字符串不是
*表示现有的常规文件,或者如果模式以
*“rw”,但给定的字符串不表示
*现有的可写常规文件和的新常规文件
*无法创建该名称,或者如果发生其他错误
*打开或创建文件时
这意味着,如果您的模式包括“r”(即“r”或“wr”),则该文件应该存在。可能是因为您没有指定正确的文件路径?是的,这一点很好。我只是想为他的异常提供一个简单的解决方案;不起作用。我必须设置一些安全设置吗?这个答案是错误的。在RandomAccessFile的Android文档中,有一个关于模式含义的表格。对于“rw”,它说,“文件被打开进行读写。如果文件不存在,它将被创建。”这似乎很清楚。“如果无法根据模式打开或创建文件”,将引发异常。此处发生的情况是由于某种原因无法创建文件。(应用程序是否要求获得必要的权限?)