我有一个在.txt
文件中存储2D数组输入的方法。然而,即使将true放在FileWriter fw = new FileWriter("CBB.dat");
的末尾(这通常允许在过去的项目中添加),文件仍然只接收一个条目,然后再用下一个条目写入它。如何解决这个问题?
public void Save(String[][] EntryList)
{
try
{
File file = new File("CBB.dat");
// if file doesnt exists, then create it
if (!file.exists())
{
file.createNewFile();
}
if (EntryList[0][0] != null)
{
DataOutputStream outstream;
outstream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
for (int row = 0; row < EntryList.length; row++)
{
for (int col = 0; col < EntryList[row].length; col++)
{
if (EntryList[row][col] != null) outstream.writeUTF(EntryList[row][col]);
}
outstream.close();
}
}
else System.out.print("Something is wrong");
} catch (IOException e)
{
e.printStackTrace();
}
}
使用CharSequence
而不是String[][]
(或者您也可以使用可变密度参数):
public static void save(CharSequence entryList)
{
BufferedReader read;
BufferedWriter write;
File file = new File("CBB.dat");
if (!file.exists())
{
try
{
file.createNewFile();
} catch (Exception e)
{
e.printStackTrace();
}
}
try
{
read = new BufferedReader(new FileReader(file));
String complete = "";
String line = null;
while ((line = read.readLine()) != null)
{
complete += line + "n";
}
read.close();
write = new BufferedWriter(new FileWriter(file));
write.append(complete);
write.append(entryList);
write.flush();
write.close();
} catch (Exception e)
{
e.printStackTrace();
}
}