OpenFileOutput()方法未定义!

16

首先,我在主活动中编写了一些方法,但我决定将它们封装成一个类。

这是我的代码... 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;
}

}


可能是重复的问题:android中的openFileOutput出了什么问题? - Michael Gaskill
@MichaelGaskill 是的,这是可能的。但这些问题已经有6年了..:) 我想,我在研究了很多之后打开了这个问题。但我不记得了,只是想想.. :) - atasoyh
2个回答

39

13

替换

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

使用以下代码行

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

如果在 Fragment 中使用

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

我正在片段中执行 getContext().openFileOutput(filename,Context.MODE_PRIVATE),它仍然有效... 我的问题是 getContext()getActivity() 之间有什么区别。 - eRaisedToX
我正在一个片段中,但是“getActivity().MODE_PRIVATE”对我没有起作用。我只是使用了Context.MODE_PRIVATE。 - madbeans

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接