2015-12-31 50 views
0

我正在使用FileOutputStream在不是我的MainActivity的活動中創建文件。該文件已創建,當我銷燬活動時,我需要的數據被寫入,但是當我從我的MainActivity重新啓動活動時,無法找到該文件。我可以在我的代碼中更改什麼,以便我沒有得到fileNotFoundException?相關的代碼是在這裏:FileOutputStream創建文件,但FileInputStream

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

我不認爲相對路徑在Android的任何意義。 – Rediska

+0

根據文件,它確實如此。 Google使用以下代碼:String FILENAME =「hello_file」; String string =「hello world!」; FileOutputStream fos = openFileOutput(FILENAME,Context.MODE_PRIVATE); fos.write(string.getBytes()); fos.close(); – samdoj

+0

這是不同的,因爲openFileOutput()在私人應用程序目錄中打開一個文件,並且FileOutputStream在文件系統中創建一個文件,所以它應該是絕對的。 – Rediska

回答

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

仍然得到一個FileNotFoundException – samdoj

+0

請確保您創建的文件沒有例外,並且您成功寫入它也確保您使用相同的文件名 – SaNtoRiaN

+0

我已經確認它創建文件沒有例外。 – samdoj

相關問題