1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
|
public class SFtpClient {
private static final String VERSION_PREFIX="~";
private ChannelSftp channel;
private boolean stopAsked=false;
protected SFtpClient(Session session) throws SshException {
try{
Channel channel=session.openChannel("sftp");
channel.connect();
this.channel=(ChannelSftp)channel;
}catch(Exception e){
throw new SshException("Cannot instantiate the SFtpClient.",e);
}
}
protected void finalize() throws Throwable
{
this.destroy();
super.finalize();
}
public void destroy(){
if(channel.isConnected()) channel.disconnect();
//System.out.println("SFtpClient destroyed.");
}
/** Interrupt any "long" task such as Get or Put.
*
*/
public void interrupt(){
this.stopAsked=true;
try {Thread.sleep(200);} catch (InterruptedException e) {}
}
public void get(File sourceFile, File destinationDir) throws SshException {
try{
GetRunnable getRunnable = new GetRunnable(this,sourceFile,destinationDir);
Thread dThread = new Thread(getRunnable);
dThread.setDaemon(true);
dThread.run();
while(dThread.isAlive()){
if(stopAsked) throw new InterruptedException();
try {Thread.sleep(100);} catch (InterruptedException e) {}
}
if(getRunnable.exception != null) throw getRunnable.exception;
}catch(Exception e){
throw new SshException("Cannot get file from \""+sourceFile+"\" to \""+destinationDir+"\".",e);
}
}
protected void _get(File sourceFile, File destinationDir) throws SftpException {
String src=SshUtils.getLinuxPath(sourceFile);
String dst=(new File(destinationDir,sourceFile.getName())).getPath();
channel.get(src, dst); //overwrite is default
}
private class GetRunnable implements Runnable{
SFtpClient sFtpClient;
File sourceFile;
File destinationDir;
public Exception exception=null;
public GetRunnable(SFtpClient sFtpClient,File sourceFile, File destinationDir){
this.sFtpClient = sFtpClient;
this.sourceFile = sourceFile;
this.destinationDir = destinationDir;
}
public void run(){
try {
sFtpClient._get(sourceFile, destinationDir);
} catch (Exception e) {
this.exception=e;
}
}
}
} |
Partager