1

我有一种将二维数组的输入存储在.txt文件中的方法。然而,即使在 的末尾加上了真正的 put 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();
    }
}
4

1 回答 1

1

使用 aCharSequence而不是 a 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();
        }
    }
于 2013-03-16T21:11:42.637 回答