Java:MyArrayList在清空ArrayList从中获取其内容的文本文件后立即清空自身
我正在用java编写自己的库,在那里可以非常简单地保存变量。但是我在改变变量的值时遇到了一个问题。一旦txt文件为空,ArrayList就会自动清空。 我的代码: 因此,当我调用Java:MyArrayList在清空ArrayList从中获取其内容的文本文件后立即清空自身,java,arraylist,Java,Arraylist,我正在用java编写自己的库,在那里可以非常简单地保存变量。但是我在改变变量的值时遇到了一个问题。一旦txt文件为空,ArrayList就会自动清空。 我的代码: 因此,当我调用setValueOf()methode时,ArrayList是空的,在txt文件中只有第一个变量+值。我的数据结构: Name=Testperson Age=40 Phone=1234 Money=1000 我的代码有什么问题?在你的SaveGameReader.read()方法中,你有result.clear()用于
setValueOf()
methode时,ArrayList是空的,在txt文件中只有第一个变量+值。我的数据结构:
Name=Testperson
Age=40
Phone=1234
Money=1000
我的代码有什么问题?在你的
SaveGameReader.read()方法中,你有result.clear()代码>用于清除ArrayList
。你甚至在打开文件之前就这么做了。所以,基本上在每次从文件读取操作之前,您都要清理现有状态并从文件中重新读取。如果文件为空,则以空列表结束
public class SaveGameReader {
private File file;
private ArrayList<String> result = new ArrayList<>();
public String getValueOf(SaveGameFile savegamefile, String variableName)
{
ArrayList<String> list = read(savegamefile);
if(list.contains(variableName))
{
return list.get(list.indexOf(variableName)+1);
}else
return null;
}
public ArrayList<String> read(SaveGameFile savegamefile) {
result.clear();
file = savegamefile.getFile();
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(file));
String read = null;
while ((read = in.readLine()) != null) {
String[] splited = read.split("=");
for (String part : splited) {
result.add(part);
}
}
} catch (IOException e) {
} finally {
boolean closed = false;
while(!closed)
{
try {
in.close();
closed=true;
} catch (Exception e) {
closed=false;
}
}
}
result.remove("");
return result;
}
}
public class SaveGameFile {
private File file;
public void create(String destination, String filename) throws IOException {
file = new File(destination+"/"+filename+".savegame");
if(!file.exists())
{
file.createNewFile();
}
}
public File getFile() {
return file;
}
public void clear() throws IOException
{
PrintWriter pw = new PrintWriter(file.getPath());
pw.close();
}
}
Name=Testperson
Age=40
Phone=1234
Money=1000