附加带有2D数组的文本文件

时间:2013-03-16 20:59:25

标签: java append multidimensional-array

我有一种方法将2D数组的输入存储在.txt文件中。但是,即使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();
    }
}

1 个答案:

答案 0 :(得分:1)

使用CharSequence代替String[][](或者您也可以使用variable arity parameters):

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