I am trying to upload file to Unix directory from java class and getting FileNotFoundException on upload and I can't see what the problem is. To upload file I am using jcraft API and error happens on this command "channelSftp.put(new FileInputStream(f), f.getName()); ". File exists, connections are working and parameters(fileName and pathToUpload are being passed correctly. Is the error because fileName directory path isn't attached with it? Browser wouldn't let me send path with it, just file name. I'll post my code if anyone have a clear solution Please post it here. Sample code would be really helpful. Thanks all.
public String uploadFile(String fileName, String pathToUpload) throws IOException {
session = UnixConnect.getInstance();
String SFTPWORKINGDIR = pathToUpload;
String result ="File failed to upload";
String fileName = new File(fileName).getName(); // file is document.pdf
Channel channel = null;
ChannelSftp channelSftp = null;
try {
channel = session.openChannel("sftp");
channel.connect();
//System.out.println("SFTP connection established");
channelSftp = (ChannelSftp)channel;
channelSftp.cd(SFTPWORKINGDIR);
File f = new File(fileName);
////////////////////////////////////////////
// file not found error in the next line.
//////////////////////////////////////////
channelSftp.put(new FileInputStream(f), f.getName());
//change mode for uploaded file
String fullpath = SFTPWORKINGDIR + fileName;
channel=session.openChannel("exec");
((ChannelExec)channel).setCommand("chmod 770 " + fullpath);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in=channel.getInputStream();
channel.connect();
result = "File " + fileName + " updloaded to directory " + SFTPWORKINGDIR;
}
catch (Exception e) {
System.out.println("Class uploadFile exception: " + e.toString());
}
finally{
if (channel != null) {
channel.disconnect();
}
}
return result;
}
Stack Trace:
08:42:02,583 ERROR [STDERR] java.io.FileNotFoundException: test.pdf
(The system cannot find the file specified) 08:42:02,583 ERROR [STDERR] at
java.io.FileInputStream.open(Native Method) 08:42:02,584 ERROR [STDERR] at
java.io.FileInputStream.<init>(FileInputStream.java:120) 08:42:02,584 ERROR [STDERR] at
spt.implement.uploadFile.uploadFile(uploadFile.java:49) 08:42:02,584 ERROR [STDERR] at
spt.controller.UploadController.doPost(UploadController.java:35) 08:42:02,584 ERROR
[STDERR] at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)