tags:

views:

359

answers:

0

I wrote following code to ftp a file:

public boolean sendFile(String sourceFilename, String destFilename) 

{ FileInputStream fis = null; Session session = null;

try { JSch jsch = new JSch(); jsch.setKnownHosts("D:/sftpRoot/test");

// Create session session = jsch.getSession(this.user, this.host, 22);

UserInfo userInfo = new MyUserInfo(); ((MyUserInfo)userInfo).setPassword(this.password); System.out.println(userInfo.getPassword()); session.setUserInfo(userInfo); session.setPassword(this.password);

// connect session.connect();

String command = "scp -p -t " + destFilename; Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command);

OutputStream out = channel.getOutputStream(); InputStream in = channel.getInputStream();

channel.connect();

//send "C0644 filesize filename" where filename doesn't contain a / long filesize = (new File(sourceFilename)).length(); command = "C0644 " + filesize + " "; if (sourceFilename.lastIndexOf('/') > 0) { command += sourceFilename.substring(sourceFilename.lastIndexOf('/') + 1); } else { command += sourceFilename; }

command += "\n";

out.write(command.getBytes()); out.flush();

//send the contents of the source file fis = new FileInputStream(sourceFilename); byte[] buf = new byte[1024]; while (true) { int len = fis.read(buf, 0, buf.length);

if (len <= 0) 
{
 break;
}

out.write(buf, 0, len);

}

fis.close(); fis = null;

//send '\0' to end it buf[0] = 0; out.write(buf, 0, 1); out.flush();

out.close();

channel.disconnect(); session.disconnect();

return true; } catch (Exception e) { e.printStackTrace(); try { if (fis != null) { fis.close(); } } catch (Exception ee) { ee.printStackTrace(); } }

return false; } The code doesnt generate any error when executed but doesnt do file upload. What am i missing?