在android上打开文件

时间:2012-07-29 19:38:22

标签: java android java-io

我想打开一个我在android中创建的文件,总是给我这个错误,主要问题是当我想打开文件时,应用程序崩溃

07-29 14:56:09.708: E/AndroidRuntime(577): java.lang.IllegalStateException: Could not execute method of the activity
07-29 14:56:09.708: E/AndroidRuntime(577):  at android.os.Handler.dispatchMessage(Handler.java:92)
07-29 14:56:09.708: E/AndroidRuntime(577):  at java.lang.reflect.Method.invokeNative(Native Method)
07-29 14:56:09.708: E/AndroidRuntime(577):  at java.lang.reflect.Method.invoke(Method.java:511)
07-29 14:56:09.708: E/AndroidRuntime(577):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
07-29 14:56:09.708: E/AndroidRuntime(577):  at dalvik.system.NativeStart.main(Native Method)
07-29 14:56:09.708: E/AndroidRuntime(577):  at java.lang.reflect.Method.invokeNative(Native Method)
07-29 14:56:09.708: E/AndroidRuntime(577):  at java.lang.reflect.Method.invoke(Method.java:511)
07-29 14:56:09.708: E/AndroidRuntime(577):  at menu.menuapp.FrontActivity.confirm(FrontActivity.java:51)
07-29 14:56:09.708: E/AndroidRuntime(577):  at libcore.io.Posix.open(Native Method)

这是保存文件的代码。

//Opening the notes file to be write.
    String notes_str = "<resource></resource>"
FileOutputStream notes_file = openFileOutput("notes.xml", Context.MODE_PRIVATE);

//Converting to string the notes_doc
String notes_str = new menu.menuapp.general().xmltostring(notes_doc);
//Saving on the file
notes_file.write(notes_str.getBytes());
//Closing the file.
notes_file.close();

这是打开文件的代码。

File file = new File("notes.xml");
FileInputStream notes_xml = new FileInputStream(file);
byte fileContent[] = new byte[(int)notes_xml.available()];
//The information will be content on the buffer.

notes_xml.read(fileContent);

String strContent = new String(fileContent);
    notes_xml.close();

1 个答案:

答案 0 :(得分:3)

打开要读取的文件时,未正确指定路径。用于File的构造函数需要完整路径,而不仅仅是文件名。

如果您使用openFileOutput()编写文件,我建议您使用openFileInput()将其读回。这样你就更有可能获得所有参数。

有关读取和写入文件的更多指导,请参阅此处:http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

此外,您的文件名在读写时也有所不同。您应该在字符串资源中定义它,或者至少在静态final中定义它。