2010-09-02 32 views
24

OpenFileOutput işlevini kullanmaya çalışıyorum ama derlemek istemiyor ... işlev tanımıyor. Ben android sdk 1.6 kullanıyorum. Bu bir sdk problemi mi? Bu bir parametre problemi mi?android openFileOutput ile ilgili sorun nedir?

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

cevap

48

Sizin yönteminiz aşağıdaki gibi olmalıdır. Ekstra bir Bağlamı parametre olarak alır. Bu yönteme size bir yolda openOutputStream olamaz Hizmetin veya Aktivite Ayrıca

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

teşekkürler, bu kadar. – Fabien

+0

Bunu işe alamadım. Burada ctx için bir bağlam, context.getApplicationContext() ', Application.instance()' ve 'Application.instance(). GetApplicationContext()' çalıştı ve her zaman FileNotFoundException atar. –

+2

Çıkıyor, bir izin sorunum vardı. Kesinlikle bir "İzin Reddedildi" sorununun bir "FileNotFoundException" ile sonuçlandığı açık değildir. –

4

Sen statik olmayan yöntem statik bağlamdan (yönteminiz statik değiştirici vardır) çağırmak çalışıyoruz. Ya yönteminizi statik olmayan veya bir Context örneğinde (çoğu durumda etkinlik örneği) geçirmeniz ve nesnede yöntemi çağırmanız gerekir.

+0

Teşekkür:

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

bir dosya nesnesi oluşturmak ve bunun gibi oluşturmanız gerekir Bunu düzeltmek için: Bu duruma neden olur. :) – Fabien

1

geçebilir. Bu sorun da öğrendim

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