2011-05-03 51 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(); 
} 
相關問題