0

我知道我会因为不理解“上下文”而受到指责,因为我完全是个菜鸟,所以我可以在一些帮助下做。

我创建了一个用于读取/写入内部存储器的基本类,但它不起作用,我相信这是一个上下文问题。该类继承了“活动”,但我不知道如何设置上下文。

类代码如下,通过以下基本代码调用:

public class GameLayer extends CCLayer {
....
  ReadWriteData myDataFile = new ReadWriteData();
  myDataFile.writeFile("Test data");
  String fileText = myDataFile.readFile();
....
}

这是课程:

public class ReadWriteData extends Activity {

  // Old line of code from original post:  public Context c = getBaseContext();
  // New line:
  public Context c = CCDirector.sharedDirector().getActivity();

  String FILENAME = "Data.dat"; 

  void writeFile(String writeText){
    FileOutputStream outputStream = null;
    try {
        outputStream = c.openFileOutput(FILENAME, Context.MODE_PRIVATE);
        outputStream.write(writeText.getBytes());
        outputStream.close();
        System.out.println("Write sucessful");
    } catch (Exception e) {
        e.printStackTrace();
    }
  }

  public String readFile(){
    String returnString = "";
    try{
        InputStream inputStreamFile = c.openFileInput(FILENAME);
        if (inputStreamFile != null){
            InputStreamReader inputStreamRdr = new InputStreamReader(inputStreamFile);
            BufferedReader bufferedReader = new         BufferedReader(inputStreamRdr);
            String fileString = "";
            StringBuilder stringBldr = new StringBuilder();
            while ((fileString = bufferedReader.readLine()) != null) {
                stringBldr.append(fileString);
            }

            inputStreamFile.close();
            returnString = stringBldr.toString();
        }           
    } catch (Exception e) {
          e.printStackTrace();
    } 
    return returnString;
  }
}
4

0 回答 0