2010-10-25 61 views
13

首先,我在主要活動中編寫了一些方法,但我決定他們應該是一個班級。OpenFileOutput()方法未定義!

這是我的代碼... openFileOutput和openFileInput是未定義的。任何想法??也許它應該是服務或活動......?

package spexco.hus.system; 

    import java.io.FileInputStream; 
    import java.io.FileNotFoundException; 
    import java.io.FileOutputStream; 
    import java.io.IOException; 
    import java.util.Date; 
    import spexco.hus.cepvizyon.CepVizyon; 
    import android.content.Context; 

    public class LicenseIDB { 
    private String PHONECODEFILE = "CepVizyonCode"; 
    private static String PhoneCode = null; 

    public LicenseIDB() { 
    if (readLocal(PHONECODEFILE, 8) == null) 
     createSystemCode(); 
} 

public static long getDate() { 
    Date currentTime = new Date(); 
    return currentTime.getTime(); 
} 

public void createSystemCode() { 
    long date = getDate(); 
    String str = Integer.toHexString(Integer.MAX_VALUE - (int) date); 
    for (int i = str.length(); i < 8; i++) { 
     str += "" + i; 
    } 
    PhoneCode = str.substring(0, 8); 
    saveLocal(PhoneCode, PHONECODEFILE); 

} 

public static String getPhoneCode() { 

    return PhoneCode; 
} 

public void saveLocal(String fileString, String Adress) { 

    try { 
     FileOutputStream fos = openFileOutput(Adress, Context.MODE_PRIVATE); 
     fos.write(fileString.getBytes()); 
     fos.close(); 
    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

public String readLocal(String Adress, int lenght) { 
    byte[] buffer = new byte[lenght]; 
    String str = new String(); 
    try { 
     FileInputStream fis = openFileInput(Adress); 
     fis.read(buffer); 
     fis.close(); 
     str = new String(buffer); 
    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    return str; 
} 

}

+0

的可能的複製[機器人有什麼不對openFileOutput?](使用HTTP://計算器.com/questions/3625837/android-what-is-wrong-with-openfileoutput) – 2016-10-31 09:04:53

+0

@MichaelGaskill是的,這是可能的。但是這些問題已經有6年了.. :)我想,在我研究了很多之後,我開了個問題。但我不記得,只是想.. :) – atasoyh 2016-11-03 13:53:43

回答

11

低於線

FileOutputStream fos = getApplicationContext().openFileOutput(filename, getActivity().MODE_PRIVATE); 

更換

FileOutputStream fos = openFileOutput(Adress, Context.MODE_PRIVATE); 

如果內部片段

FileOutputStream fos =getActivity().openFileOutput(filename, getActivity().MODE_PRIVATE); 
+0

我正在做'getContext()。openFileOutput(文件名,Context.MODE_PRIVATE)'裏面的一個片段,它仍然有效....我的問題是有什麼區別在'getContext()'和'getActivity()'之間。 – eRaisedToX 2017-04-19 09:54:14