【发布时间】:2015-12-31 02:54:15
【问题描述】:
我正在使用FileOutputStream 在不是我的MainActivity 的活动中创建文件。文件已创建,当我销毁活动时,会写入我想要的数据,但是当我从MainActivity 重新启动活动时,找不到该文件。我可以在我的代码中进行哪些更改,以免我收到fileNotFoundException?相关代码在这里:
try {
fis = new FileInputStream("words");
ois = new ObjectInputStream(fis);
} catch (FileNotFoundException e1) {
fnfexception = e1;
} catch (IOException ioe) {
ioe.printStackTrace();
}
EOFException eof = null;
int counter = 0;
if (fnfexception == null) {
while (eof == null) {
try {
if (words == null) words = new Dict[1];
else words = Arrays.copyOf(words, counter + 1);
words[counter] = (Dict) ois.readObject();
counter++;
} catch (EOFException end) {
eof = end;
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
}
}
wordStartCount = counter;
wordCount = counter;
fnfexception = null;
try {
fos = openFileOutput("words", Context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
} catch (FileNotFoundException e1) {
fnfexception = e1;
} catch (IOException ioe) {
ioe.printStackTrace();
}
【问题讨论】:
-
我认为相对路径在 Android 中没有任何意义。
-
根据文档,确实如此。 Google 使用以下代码: String FILENAME = "hello_file"; String string = "你好世界!"; FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); fos.write(string.getBytes()); fos.close();
-
这个不同,因为openFileOutput()在私有app目录下打开一个文件,而FileOutputStream在文件系统中创建一个文件,所以应该是绝对的。
-
不要写这样的代码,所有的异常引用。取决于
try块中代码是否成功的代码应该在同一个try块内。
标签: java android file exception fileinputstream