【问题标题】:FileOutputStream creates a file, but FileInputStreamFileOutputStream 创建一个文件,但 FileInputStream
【发布时间】: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


【解决方案1】:

你使用了错误的方式读取内部文件,使用下面的代码

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();
}

【讨论】:

  • 仍然得到 FileNotFoundException
  • 确保您创建的文件没有例外,并且您已成功写入文件并确保您使用相同的文件名
  • 我已经确认它会毫无例外地创建文件。
  • 你可能使用了错误的文件名,在我的代码中我只是使用了file_name,用你自己的文件名替换它
  • 是的,我的意思是在我的代码中我使用“file_name”作为文件名。在您的文件中,使用“单词”,因为它是您用于创建文件的名称
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-09
  • 2019-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-28
相关资源
最近更新 更多