Skip to content

SFTP Append doesn't work [?] #390

@IgnatBeresnev

Description

@IgnatBeresnev

I've been trying to append text to the end of the file with OpenMode.APPEND, but no luck so far. It seems to ignore this flag and just uses the offset. If I set the offsets (both file & off) to 0, then it'll rewrite the file. How do I go about appending text to the end of the file WITHOUT offsets and ONLY with OpenMode.APPEND, if it's possible?

Here's how I'm trying to do it

String fileName = "test_write_continuously.txt";
String filePath = HOME_FOLDER + "/" + fileName;

String initialText = "This is initial text of the file. ";
byte[] bytes = initialText.getBytes();

RemoteFile writeInitial = sftpClient.open(filePath, new HashSet<>(Arrays.asList(OpenMode.WRITE, OpenMode.CREAT)));
writeInitial.write(0, bytes, 0, bytes.length);
writeInitial.close();

String appendText = "This is the continuation text that should be appended after initial. ";
byte[] appendTextBytes = appendText.getBytes();

RemoteFile writeAppend = sftpClient.open(filePath, new HashSet<>(Arrays.asList(OpenMode.WRITE, OpenMode.APPEND)));
writeAppend.write(0, appendTextBytes, 0, appendTextBytes.length);
writeAppend.close();

RemoteFile readContent = sftpClient.open(filePath, new HashSet<>(Arrays.asList(OpenMode.READ)));
byte[] readBytes = new byte[bytes.length + appendTextBytes.length];
readContent.read(0, readBytes, 0, readBytes.length);
String readString = new String(readBytes);
readContent.close();

assertEquals(initialText + appendText, readString);

What I want to achieve: continuously write to the end of the file, pretty much real-time logging on a remote server through ssh, and I need the data to be consistent and in order. You think it's possible to achieve? So far I've been having file rewrites

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions