我正在Android中创建一个小游戏,现在我想将一个文件用作存档游戏。 在开始时它会检查是否已经有一个存档游戏,如果没有,它应该创建它。如果有一个存档游戏,它应该阅读它。当你关闭应用程序/关闭手机/等。它应该保存它。 为了编码这个,我google了一下,找到了一些东西,但似乎它不起作用,但我不知道为什么。以下是我班级的相关片段:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
FileStart();
}
public void FileStart() {
File external = getFilesDir();
String path = external.getPath();
File file = new File(path + "inv.txt");
if(file.exists()) {
//read files
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String result = in.readLine();
String[] resultSplit = result.split("|");
fruits = Integer.parseInt(resultSplit[0]);
milk = Integer.parseInt(resultSplit[1]);
sugar = Integer.parseInt(resultSplit[2]);
wheat = Integer.parseInt(resultSplit[3]);
cake = Integer.parseInt(resultSplit[4]);
in.close();
TextView tView = new TextView(this);
tView=(TextView)findViewById(R.id.textView1);
tView.setText(fruits + " x Fruits");
tView=(TextView)findViewById(R.id.textView3);
tView.setText(milk + " x Milk");
tView=(TextView)findViewById(R.id.textView4);
tView.setText(sugar + " x Sugar");
tView=(TextView)findViewById(R.id.textView5);
tView.setText(wheat + " x Wheat");
tView=(TextView)findViewById(R.id.textView9);
tView.setText(cake + " Cakes");
} catch (Exception e) {
e.printStackTrace();
}
} else {
try {
file.createNewFile();
FileWriter filewriter = new FileWriter(file);
BufferedWriter out = new BufferedWriter(filewriter);
out.write("0|0|0|0|0");
out.flush();
out.close();
filewriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
protected void onPause () {
super.onPause(); // Always call the superclass method first
//save game progress
File external = getFilesDir();
String path = external.getPath();
File file = new File(path + "inv.txt");
try {
FileWriter filewriter = new FileWriter(file);
BufferedWriter out = new BufferedWriter(filewriter);
String toWrite = fruits + "|" + milk + "|" + "|" + sugar + "|" + wheat + "|" + cake;
out.write(toWrite);
out.flush();
out.close();
filewriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
答案 0 :(得分:0)
使用以下代码创建目录:
boolean success = (new File(getApplicationContext().getFilesDir()+"/YourFolderName")).mkdir();
if (!success){
Log.w("directory not created", "directory not created");
}