【发布时间】:2014-02-24 16:25:16
【问题描述】:
我正在 Android 中创建一个小游戏,现在我想使用一个文件作为存档游戏。 在开始时它会检查是否已经有一个存档游戏,如果没有,它应该创建它。如果有存档游戏,它应该阅读它。当您关闭应用程序/关闭手机/等时。它应该保存它。 为了编写代码,我用谷歌搜索了一下,发现了一些东西,但似乎它不起作用,但我不知道为什么。这是我班的相关sn-ps:
@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();
}
}
【问题讨论】:
-
文件创建了吗?你面临什么问题?什么不工作?
-
文件好像没有创建。我是否必须创建带有“getFilesDir();”的文件夹?第一?
-
是的,当然,getFilesDir();将为您提供应用程序文件夹,该文件夹位于内部存储器上,并且适合,当用户卸载您的应用程序时,该文件夹也将被删除。
-
@NunChai 嗯,我试图创建目录“文件外部 = getFilesDir(); external.mkdirs();”但是,它不是创建的 - 你知道吗?