Java:一旦我清空了 ArrayList 从中获取其内容的文本文件,我的 ArrayList 就会自行清空



我正在用java编写自己的库,您可以在其中非常简单地保存变量。但是我在更改变量的值时遇到问题。一旦 txt 文件为空,ArrayList 就会自行清空。 我的代码:

public class SaveGameWriter {
private File file;
private boolean closed = false;
public void write(SaveGameFile savegamefile, String variableName, String variableValue, SaveGameReader reader) throws FileNotFoundException
{
if(!reader.read(savegamefile).contains(variableName))
{
file = savegamefile.getFile();
OutputStream stream = new FileOutputStream(file, true);
try {
String text = variableName+"="+variableValue;
stream.write(text.getBytes());
String lineSeparator = System.getProperty("line.separator");
stream.write(lineSeparator.getBytes());
}catch(IOException e)
{}
do {
try {
stream.close();
closed = true;
} catch (Exception e) {
closed = false;
}
} while (!closed);
}
}
public void setValueOf(SaveGameFile savegamefile, String variableName, String Value, SaveGameReader reader) throws IOException
{
ArrayList<String> list = reader.read(savegamefile);
if(list.contains(variableName))
{
list.set(list.indexOf(variableName), Value);
savegamefile.clear();
for(int i = 0; i<list.size()-1;i+=2)
{
write(savegamefile,list.get(i),list.get(i+1),reader);
}
}
}
}

这是我的SaveGameReader类:

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;
}
}

还有我的 SaveGameFile 类:

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();
}
}

因此,当我调用setValueOf()方法时,ArrayList 是空的,在 txt 文件中只有第一个变量 + 值。Hier是我的数据结构:

Name=Testperson
Age=40
Phone=1234
Money=1000

我的代码有什么问题?

在您的SaveGameReader.read()方法中,您有清除ArrayListresult.clear();。您甚至可以在打开文件之前执行此操作。因此,基本上在每次从文件读取操作之前,您都会清理现有状态并从文件中重新读取。如果文件为空,则以空列表完成

最新更新