sshj icon indicating copy to clipboard operation
sshj copied to clipboard

"No such file" error while closing RemoteFile

Open elwira-zimoch opened this issue 2 years ago • 3 comments

Hi, I am getting "no such file" exception while calling close on RemoteFile object (file.close() below).

public void get(String path, CheckedConsumer<InputStream> consumer) throws SSHException {
        try  {
           SFTPClient client = sshClient.newSFTPClient();
            final RemoteFile file = client.getSFTPEngine().open(path, EnumSet.of(OpenMode.READ));
           InputStream inputStream = getInputStream(file);
        } finally {
            if (inputStream != null) {
                    inputStream.close();
             }
           .....
        }
    }
 private RemoteFile.RemoteFileInputStream getInputStream(RemoteFile file) {
        return file.new RemoteFileInputStream() {
            @Override
            public void close() throws IOException {
                try (file) {
                    super.close();
                } finally {
                    file.close();
                }
            }
        };
    }

Here is info from stacktrace: net.schmizz.sshj.sftp.SFTPException: No such file at net.schmizz.sshj.sftp.Response.error(Response.java:140) at net.schmizz.sshj.sftp.Response.ensureStatusIs(Response.java:133) at net.schmizz.sshj.sftp.Response.ensureStatusPacketIsOK(Response.java:125) at net.schmizz.sshj.sftp.RemoteResource.close(RemoteResource.java:55)

elwira-zimoch avatar Dec 02 '22 13:12 elwira-zimoch

@elwira-zimoch The close() method in the anonymous class appears to be effectively calling close twice:

  1. try (file) { is a try-with-resources, which calls RemoteFile.close()
  2. finally { file.close(); } calls RemoteFile.close()

The finally { file.close() } block is unnecessary with the try-with-resources, so the method should work as follows:

@Override
public void close() throws IOException {
    try (file) {
        super.close();
    }
}

exceptionfactory avatar Dec 14 '22 02:12 exceptionfactory

@exceptionfactory you are right, thank you. Is there any correct way to find out weather RemoteFile/ RemoteFileInput(Output)Stream has been closed correctly? I've looked through the repo and could not find anything that would be helpful in such situation.

elwira-zimoch avatar Dec 30 '22 08:12 elwira-zimoch

You're welcome @elwira-zimoch. As both RemoteFile and RemoteFileInputStream implement or extend standard interfaces (Closeable and InputStream), the best approach is to follow standard strategies for handling those types of resources.

exceptionfactory avatar Dec 30 '22 17:12 exceptionfactory