Sumanth
Sumanth

Reputation: 605

JSch put file into a subdirectory

I am trying to place a file into SFTP directory using JSch.

channelSftp.cd(destDir);
channelSftp.put(new FileInputStream(filePath), filePath.substring(filePath.lastIndexOf(File.separatorChar)));

But the above code is placing the file always in the SFTP user home directory instead of destDir. For example, if I create a subdirectory test under user home directory and set destDir as channelSftp.getHome()+"test", still the file is being copies to user home directory only instead of test sub-directory.

I tried to list files in destDir (test sub-directory), it is showing all files/directories under test directory.

Vector<com.jcraft.jsch.ChannelSftp.LsEntry> vv = channelSftp.ls(destDir);
if(vv != null) {
     for(int ii=0; ii<vv.size(); ii++){
         Object obj=vv.elementAt(ii);
         if(obj instanceof LsEntry){
             System.out.println(((LsEntry)obj).getLongname());
         }
     }
 }

Any suggestions? I looked at permissions (test sub-directory has exactly same permissions as SFTP user home directory).

Upvotes: 2

Views: 5541

Answers (2)

Dan Ortega
Dan Ortega

Reputation: 1899

This works for very well !!

       channel.connect();

       try {
          channel.mkdir("subdir");
       } catch (Exception e) {
          // ... do something if subdir already exists
       }

       // Then the trick !
       channel.put(inputStream, "subdir" + "/" + "filename.ext");

Upvotes: 0

Martin Prikryl
Martin Prikryl

Reputation: 202158

filePath.substring(filePath.lastIndexOf(File.separatorChar)) result includes even the last separator.

So if you pass /home/user/file.txt, you get /file.txt. That is an absolute path, so any working directory is disregarded and you effectively always write to a root folder.

You want filePath.substring(filePath.lastIndexOf(File.separatorChar) + 1) to get only file.txt.

See also How do I get the file name from a String containing the Absolute file path?

Upvotes: 2

Related Questions