简体   繁体   English

FileOutputStream创建一个文件,但是FileInputStream

[英]FileOutputStream creates a file, but FileInputStream

I am using a FileOutputStream to create a file in an activity that is not my MainActivity . 我正在使用FileOutputStream在不是MainActivity的活动中创建文件。 The file is created, and when I destroy the activity, the data I want is written, but when I relaunch the activity from my MainActivity , the file cannot be found. 创建文件后,销毁活动时,将写入所需的数据,但是当我从MainActivity重新启动活动时,找不到文件。 What can I change in my code so that I don't get a fileNotFoundException ? 我可以在代码中进行哪些更改,以免出现fileNotFoundException The relevant code is here: 相关代码在这里:

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

You used wrong way to read from an internal file, use the following code 您使用错误的方式读取内部文件,请使用以下代码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM