2010-09-02 67 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()); 
}