文件处理:即使在使用追加后也会创建一个新文件

File Handling: A new file is created even after using append

所以,我试图在我的内部存储中创建一个文件,但以下代码总是创建一个新文件,并且只在文件中存储最新的字符串。以下代码的一部分(try{})被使用了两次。有人可以告诉我我做错了什么吗?在第一种情况下,消息由我们发送并传输到 listview 并复制到文件中作为备份,在第二种情况下,消息发送给我们并传输到 listview,再次将字符串备份在文件。

File file = new File("/storage/emulated/0/BlueChat.txt");

private Handler handler = new Handler(new Handler.Callback() {

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {

            case MESSAGE_WRITE:
                byte[] writeBuf = (byte[]) msg.obj;

                String writeMessage = new String(writeBuf);
                chatMessages.add("Me: " + writeMessage);
                chatAdapter.notifyDataSetChanged();
                try
                {
                        if (!file.exists())
                        {
                            file.createNewFile();
                        }
                        else
                        {
                            FileWriter fw = new FileWriter(file.getAbsoluteFile());

                            fw.append("Me: " + writeMessage);
                            fw.close();
                        }
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }

                break;
            case MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;

                String readMessage = new String(readBuf, 0, msg.arg1);
                chatMessages.add(connectingDevice.getName() + ":  " + readMessage);
                chatAdapter.notifyDataSetChanged();

                try
                {
                    if (!file.exists())
                    {
                        file.createNewFile();
                    }
                    else
                    {
                        FileWriter fw = new FileWriter(file.getAbsoluteFile());

                        fw.append(connectingDevice.getName() + ":  " + readMessage);
                        fw.close();
                    }
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }

                break;

        }
        return false;
    }
});

而不是使用

FileWriter fw = new FileWriter(file.getAbsoluteFile());

使用

FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);

看一下FileWriter的第二个构造函数class:

FileWriter(String fileName, boolean append)

Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.

更多信息在这里:https://developer.android.com/reference/java/io/FileWriter#public-constructors