我找不到任何相关内容(即使有Parse-Questions的内容):
与一个好的旧网站计数器类似,我喜欢将数字存储在SD卡上的txt文件中。每次在应用程序中激活方法时,它应该读取一些txt文件,添加1并再次保存。
如果我尝试下面的代码,它会创建一个奇怪的字符串,而不是Int。如何解决这个问题呢? : - (
FileWriter writer;
File file;
FileInputStream fileIS;
public void implementCounter()
{
File sdcard = Environment.getExternalStorageDirectory();
int counter = 0;
try{
File f = new File(sdcard +"/Experiment/Counter.txt");
fileIS = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
//counter = Integer.parseInt(buf.readLine());
String readString = new String();
//just reading each line and pass it on the debugger
/*while((readString = buf.readLine())!= null){
Log.d("line: ", readString);
}*/
readString = buf.readLine();
try {
counter = Integer.parseInt(readString.toString());
} catch(NumberFormatException nfe) {
Log.d("line: ", "XXX: " + readString + "E");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
//Create / Write LogFile
file = new File(sdcard + "/Experiment/Counter.txt");
try
{
counter++;
writer = new FileWriter(file ,false);
writer.write(counter);
writer.flush();
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
这个想法是,新的FileWriter只是用一个数字覆盖旧文件。
答案 0 :(得分:0)
这两个功能是静态的。您可以使用它们来检索您的计数并保存它(设置它)。有关详细信息,请尝试熟悉SharedPreferences。不客气(
private static boolean setMyLovelyCount(Context mContext, int value) {
SharedPreferences prefs = mContext.getSharedPreferences(
"mylovelyprefs", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("mylovelyCount", value);
return editor.commit();
}
private static int getMyLovelyCount(Context mContext, int defaultvalue) {
SharedPreferences prefs = mContext.getSharedPreferences(
"mylovelyprefs", 0);
return prefs.getInt("mylovelyCount", defaultvalue);
}