2010-09-02 68 views
24

我試圖使用openFileOutput函數,但它不想編譯...不認識de函數。我使用android sdk 1.6。這是一個sdk問題嗎?這是一個參數問題嗎?android openFileOutput有什麼問題?

import java.io.FileOutputStream; 
public static void save(String filename, MyObjectClassArray[] theObjectAr) { 
     FileOutputStream fos; 
     try { 
      fos = openFileOutput(filename, Context.MODE_PRIVATE); 


      ObjectOutputStream oos = new ObjectOutputStream(fos); 
      oos.writeObject(theObjectAr); 
      oos.close(); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     }catch(IOException e){ 
      e.printStackTrace(); 
     } 
    } 

回答

48

你的方法應該如下。採用額外的上下文作爲參數。這種方法,你可以通過你的服務或活動

public static void save(String filename, MyObjectClassArray[] theObjectAr, 
    Context ctx) { 
     FileOutputStream fos; 
     try { 
      fos = ctx.openFileOutput(filename, Context.MODE_PRIVATE); 


      ObjectOutputStream oos = new ObjectOutputStream(fos); 
      oos.writeObject(theObjectAr); 
      oos.close(); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     }catch(IOException e){ 
      e.printStackTrace(); 
     } 
    } 
+0

謝謝,就是這樣。 – Fabien 2010-09-02 10:06:27

+0

我無法得到這個工作。我在這裏爲ctx嘗試了一個傳遞的上下文,context.getApplicationContext(),Application.instance()和Application.instance()。getApplicationContext(),它總是拋出FileNotFoundException異常。 – 2011-05-23 08:16:28

+2

原來,我有一個權限問題。絕對不明顯的是,「權限被拒絕」問題導致了「FileNotFoundException」。 – 2011-05-23 21:24:36

4

您試圖從靜態上下文中調用非靜態方法(您的方法有靜態修飾符)。您必須使您的方法成爲非靜態或傳遞Context的實例(大多數情況下爲活動實例)並在該對象上調用該方法。

+0

感謝我發現也是這個問題。 :) – Fabien 2010-09-02 10:05:19

1

你也不能openOutputStream的道路。這導致該異常:

java.lang.IllegalArgumentException: File /storage/sdcard0/path/to/file.txt contains a path separator 

要解決這個問題,你需要創建一個文件對象並創建它是這樣的:

String filename = "/sdcard/path/to/file.txt"; 
File sdCard = Environment.getExternalStorageDirectory(); 
filename = filename.replace("/sdcard", sdCard.getAbsolutePath()); 
File tempFile = new File(filename); 
try 
{ 
    FileOutputStream fOut = new FileOutputStream(tempFile); 
    // fOut.write(); 
    // fOut.getChannel(); 
    // etc... 
    fOut.close(); 
}catch (Exception e) 
{ 
    Log.w(TAG, "FileOutputStream exception: - " + e.toString()); 
}