我知道我会因为不理解'背景'而受到谴责,因为我是一个完全的菜鸟,所以我可以做一些帮助。
我已经创建了一个用于读取/写入内部存储器的基本类,但它不起作用,我认为这是一个上下文问题。该类继承了“活动”,但我不知道如何设置上下文。
下面是类代码,通过以下基本代码调用:
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;
}
}