javalinuxsmb

How to copy/transfer a file from windows server path to linux server path?


I have tried the below code:

String url = "smb://remotehost/SharedPath/Comp/NG/";
NtlmPasswordAuthentication auth2 = new 
NtlmPasswordAuthentication(null,"user", "password");
SmbFile dir = new SmbFile(url, auth);
for (SmbFile f : dir.listFiles())
{
  if(f.getName().contains("Test")) //successfully reads the file
  {
    System.out.println("test...."+f);
    filename= f.getUncPath();
    System.out.println("filename...."+filename);
    sftpChannel.put(filename, remoteDirectory); // throws exception
  }  
}

Above code results in exception as follows: java.io.FileNotFoundException: \\remotehost\SharedPath\comp\NG\Test.txt (Logon failure: unknown user name or bad password)

Please note:

Please note: I am connecting to Linux server using jsch library and I am able to successfully connect to Linux server using sftpChannel.connect(); and also able to put the file from my local machine to Linux server using sftpChannel.put(localpath, linuxpath); and To connect to windows server I am using smbFile. I am able to connect but not able to copy the file from windows to Linux server path. I tried using sftpChannel.put(filename, remoteDirectory); for the same but it resulted in exception. At this particular step I assumed that as the connection to windows server is successful I will be able to copy the files as well. I am able to read the file but not copy. Not sure why this is happening.

Can anyone provide me the proper steps to do this?


Solution

  • I guess the type of sftpChannel is com.jcraft.jsch.ChannelSftp. Then the following method will do the copy for you. Of course you have to pass properly initialized SmbFile and ChannelSftp objects as parameters.

    public void copyFromSmbToSftp(SmbFile smbFile, ChannelSftp channelSftp, String destPath) throws IOException, SftpException {
        try(BufferedInputStream inputStream = new BufferedInputStream(smbFile.getInputStream());
            BufferedOutputStream outputStream = new BufferedOutputStream(channelSftp.put(destPath))){
          byte[] buffer = new byte[64*1024];
          int bytesRead;
          while((bytesRead=inputStream.read(buffer, 0, buffer.length))!=-1){
            outputStream.write(buffer, 0, bytesRead);
          }
        }
      }