我正在尝试将用户选择的首选项保存到文本文件中。当我保存某些内容然后尝试向其添加信息时,它会被覆盖。我检查了日志,看来当我读取文件以检查之前是否有任何内容写入时,它只读取3行,即使我检查了文件,它有6行。
我使用savefiles
方法下面编写的类SoundDetails
实例调用名为saveFiles
的方法:
public static void saveFiles(SoundDetails s) {
try {
Scanner readDatabasetoSave = new Scanner(file);
PrintWriter write = new PrintWriter(file);
String everyThing = "";
while(readDatabasetoSave.hasNext()){
everyThing += readDatabasetoSave.nextLine();
Log.e(everyThing, everyThing);
}
int index = everyThing.indexOf('#');
if(index != -1){
everyThing = everyThing.substring(0,index);
}
everyThing = everyThing + s.name + "\n" +s.time + "\n" + s.onoff +"\n";
Log.d("everything final", everyThing);
//Log.e("everything",everyThing);
for(boolean b : s.daysofweek){
if(b == true){
everyThing += "T";
}
else{
everyThing += "F";
}
}
everyThing += "\n";
for(boolean b : s.sensors){
if(b == true){
everyThing += "T";
}
else{
everyThing += "F";
}
}
everyThing += "\n"+s.profile+"#";
write.print(everyThing);
write.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("error occured", e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这是SoundDetails
类:
public class SoundDetails {
public boolean[] sensors ; // wifi gps 3g bluetooth airplane
public boolean[] daysofweek ;
public boolean onoff ;
public String profile;
public String name;
public String time;
public SoundDetails(boolean[] sensors, boolean[] daysofweek,String profile,boolean onoff,String name,String time){
this.sensors = sensors;
this.daysofweek = daysofweek;
this.profile = profile;
this.onoff = onoff;
this.name = name;
this.time = time;
}
}
答案 0 :(得分:0)
int index = everyThing.indexOf('#');
if(index != -1){
everyThing = everyThing.substring(0,index);
}
...当你用其余代码判断时,我想你实际上在寻找最后一个索引:
int index = everyThing.lastIndexOf('#');
if(index != -1){
everyThing = everyThing.substring(0,index);
}
此外,在关闭流之前刷新流通常是个好主意:
write.print(everyThing);
write.flush(); //since the printwriter you're using does not autoflush
write.close();
答案 1 :(得分:0)
如果您问题的第一行是准确的(“我正在尝试将用户选择的首选项保存到文本文件中。”)那么我想知道您是否只是做了太多的工作。
您是否有特定原因未使用内置偏好设置管理器ala http://developer.android.com/guide/topics/ui/settings.html?