【发布时间】:2014-10-05 16:42:42
【问题描述】:
在我的应用程序中,我将游戏中的数据保存到 .txt file.
我现在遇到的问题是,如果游戏时间超过一分钟,文本文件的 String 名称会导致文件被分成两部分。
例如如果它在9.22am 和9.23am 上播放,则会创建两个单独的文件。
如何创建一个更合适的文件名,该文件名对每个文件都是唯一的。
与文本文件名称相关的代码:
Time t= new Time();
t.setToNow();
int timeFileMinute= t.minute;
int timeFileDate= t.yearDay;
int timeFileYear= t.year;
//creating file name
String fileName= "Maths-" +timeFileMinute + timeFileDate + timeFileYear + android.os.Build.SERIAL;
完全写入文件方法:
public void writeToFileEEGPower(String data){
Time t= new Time();
t.setToNow();
int timeFileMinute= t.minute;
int timeFileDate= t.yearDay;
int timeFileYear= t.year;
//creating file name
String fileName= "Maths-" +timeFileMinute + timeFileDate + timeFileYear + android.os.Build.SERIAL;
//creating the file where the contents will be written to
File file= new File(dir, fileName + ".txt");
FileOutputStream os;
try{
boolean append= true;
os= new FileOutputStream(file, append);
String writeMe =data + "\n";
os.write(writeMe.getBytes());
os.close();
} catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
【问题讨论】:
-
我不明白。如果您不想在 txt 的文件名中使用时间,为什么?
-
您的问题是您不断重新导出文件名。您可能应该决定什么构成会话(在 Android 上相当重要,除非您的游戏定义了“结束”),通过您选择的任何方法创建文件名,然后在会话期间使用相同的名称.
-
不要在 writeToFileEEGPower() 方法中分配文件名,而是创建一个类级变量并在构造函数中分配它。
-
@Adrian - 是的,作为一种基本机制,但 Android 可能会在明显的用户会话中保留 Activity 类的实例数小时或数天。因此,可能需要使用一些针对此特定应用程序所需的用户体验进行调整的逻辑来决定何时开始新会话并分配新文件名。