0

Is there any way to lock file, which i am reading with JSch sftp channel, to prevent other applications to modificate it while session is open?

The problem i have: while i am reading/writing file, some other application changes the file and its causes errors.

Currently i am reading file in such way:

ChannelSftp sftp = (ChannelSftp) session.openChannel("sftp");

InputStream stream = sftp.get("/some/file");
try {
    BufferedReader br = new BufferedReader(new InputStreamReader(stream));
    // read from br
} finally {
    stream.close();
}
Vololodymyr
  • 1,996
  • 5
  • 26
  • 45
  • 1
    possible duplicate of [SFTP file lock mechanism](http://stackoverflow.com/questions/26932341/sftp-file-lock-mechanism) – Kenster Mar 30 '15 at 17:02

2 Answers2

1

Rather than locking the file (which could adversely affect whatever application you suggest is changing the file), and presuming you have ssh access and permissions to do so you could copy the file into a temp file using an ssh command (if on a 'nix system: 'cp /some/file/ /some/temp/file/'), which in all likelihood will be much faster than transferring via scp. (See http://www.jcraft.com/jsch/examples/Exec.java.html for exec example). From there, scp-get the temp file. Lastly, if necessary, delete the temp file via an other JSch exec command.

copeg
  • 8,290
  • 19
  • 28
  • 1
    This isn't a very general solution. The OP may not have plain ssh access to the remote server. The remote server may not be unix-based, so it's not obvious what command to run to make a copy. He may not have access to a directory on the remote where can create files. – Kenster Mar 30 '15 at 16:38
  • Thanks for the clarification. I updated my answer a bit to take into consideration your points – copeg Mar 30 '15 at 17:38
1

Jsch at this time supports version 3 of the SFTP protocol. The wikipedia page contains links to different versions of the protocol. Version 3 is here, and the word "lock" doesn't appear anywhere in it. In other words, the protocol doesn't support locking, so there's nothing for Jsch to support.

SFTP versions 5 and 6 do contain support for locking remote files. However, Jsch doesn't support these protocol versions.

I'll add that OpenSSH, the most widely used SSH/SFTP server, only supports SFTP version 3. You'd have to use some other server software to have any hope of doing file locks.

Community
  • 1
  • 1
Kenster
  • 23,465
  • 21
  • 80
  • 106