sshj
sshj copied to clipboard
"No such file" error while closing RemoteFile
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 The close()
method in the anonymous class appears to be effectively calling close twice:
-
try (file) {
is a try-with-resources, which callsRemoteFile.close()
-
finally { file.close(); }
callsRemoteFile.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 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.
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.