FileOutputStream创建一个文件,但FileInputStream

时间:2015-12-31 02:54:15

标签: java android file exception fileinputstream

我正在使用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();
}

1 个答案:

答案 0 :(得分:0)

您使用错误的方式从内部文件中读取,请使用以下代码

try {
    FileInputStream fis = context.openFileInput("file_name");
    int content;
    StringBuilder str = new StringBuilder();
    while ((content = fis.read()) != -1)
        str.append((char) content);
    fis.close();
    String savedText = str.toString();
} catch (IOException e) {
    e.printStackTrace();
}