我找不到任何相关的东西(即使有数百个解析问题):
类似于一个好的旧网站计数器,我喜欢将一个数字存储在 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 只是用高一个数字覆盖旧文件。