2011-05-03 50 views
3

我的Activity类调用另一个非活动类,当我尝试使用openFileOutput时,我的IDE告诉我openFileOutput是未定义的。请帮忙:在类中使用openFileOutput()。 (不是活动)

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.io.*; 

import android.util.Log; 
import android.content.Context; 

public class testFile(){ 

Context fileContext; 

public testFile(Context fileContext){ 
    this.fileContext = fileContext; 
} 

public void writeFile(){ 
    try{ 
      FileOutputStream os = fileContext.getApplicationContext().openFileOutput(fileLoc, Context.MODE_PRIVATE); 
     os.write(inventoryHeap.getBytes()); // writes the bytes 
     os.close(); 
     System.out.println("Created file\n"); 
    }catch(IOException e){ 
     System.out.print("Write Exception\n"); 
    } 
} 
} 

回答

0

我删除我的答案从之前的,因为我错了,我看到的问题是,你添加()到类声明:public class testFile(){。它应该是public class testFile{。就这样。

+0

感谢您的帮助。你之前的回答是正确的。我只是输入我的例子错了,这就是为什么我有公共类testFile(){ – ddan 2011-05-04 21:24:10

+0

这很有趣你说的这样,因为使用你的确切例子,但只有在我写在这个答案的修复,我没有错误... – MByD 2011-05-04 21:56:49

+0

好的...我刚刚做到了。我有非活动类扩展我的活动类。我在我的非活动类中取出了getContextApplication()。我还将fileContext的类型更改为Activity。 – ddan 2011-05-05 11:15:26

2

你已经有了上下文。

FileOutputStream os = fileContext.openFileOutput(fileLoc, Context.MODE_PRIVATE); 
0

你可以试着改变Context fileContext;static Context fileContext;

0

我在写这更适合我比谁都清楚。我是Android编程的新手。我遇到了同样的问题,并通过将上下文作为参数传递给方法来解决问题。在我的例子中,类正在尝试使用我在Java示例中找到的一段代码写入文件。因为我只是想写一个对象的持久性,并没有想和关心自己的“地方”的文件,我修改了以下内容:

public static void Test(Context fileContext) { 
    Employee e = new Employee(); 
    e.setName("Joe"); 
    e.setAddress("Main Street, Joeville"); 
    e.setTitle("Title.PROJECT_MANAGER"); 
    String filename = "employee.ser"; 
    FileOutputStream fileOut = fileContext.openFileOutput(filename, Activity.MODE_PRIVATE); // instead of:=> new FileOutputStream(filename); 
    ObjectOutputStream out = new ObjectOutputStream(fileOut); 
    out.writeObject(e); 
    out.close(); 
    fileOut.close(); 
} 

,并从我使用调用活动如下:

SerializableEmployee.Test(this.getApplicationContext()); 

工作就像一个魅力。然后我可以阅读(简化版):

public static String Test(Context fileContext) { 
    Employee e = new Employee(); 
    String filename = "employee.ser"; 
    File f = new File(filename); 
    if (f.isFile()) { 
    FileInputStream fileIn = fileContext.openFileInput(filename);// instead of:=> new FileInputStream(filename); 
    ObjectInputStream in = new ObjectInputStream(fileIn); 
    e = (Employee) in.readObject(); 
    in.close(); 
    fileIn.close(); 
    } 
    return e.toString(); 
} 
相关问题