#writing to file overrides

10 messages · Page 1 of 1 (latest)

buoyant estuary
#

i have

    public void write(File file, String string) {
        Path path = file.toPath();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.put(string.getBytes());
        buffer.flip();
        try(AsynchronousFileChannel asyncChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE)){
            Future<Integer> future =  asyncChannel.write(buffer, 0);
            while(!future.isDone()) {
            }
            buffer.clear();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }```
which writes to a file fine but it only writes to the 1st line and will override what is already there, i just want it to write the text to the line bellow
gusty ravineBOT
#

This post has been reserved for your question.

Hey @buoyant estuary! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

terse hazel
#

Use the class FileWriter, it can write to the next line using the append method

cold comet
#

All ways to write in a file support the append option one way or another, that I know of.

terse hazel
#

AsynchronousFileChannel does not have an append function, you would just need to know the position you want to write at

#

It’s overriding the first line because asyncChannel.write(buffer, 0) would write to position 0.

cold comet
#

And that still wouldn't be a reason to recommand FileWriter rather than Files.write()

terse hazel
#

I don’t know that was just the first thing I thought of