-2

I'm downloading a file from remote server using sftp channel as inputstream and trying to cast into fileinputstream. Then I'm receiving following exception from jvm 1.8

java.lang.ClassCastException: com.jcraft.jsch.ChannelSftp$2 cannot be cast to java.io.FileInputStream

Please someone help. I'm stuck here

  • 2
    You need to show the relevant part of your code. Anyway: you try to cast something into something that it cannot be cast into because the types are not related to each other. – luk2302 Nov 28 '18 at 16:42
  • Whatever the `Channel.getInputStream()` method returns, it is never a `FileInputStream`. `FileInputStream`s are only created if you open a local file for reading. – Thomas Kläger Nov 28 '18 at 17:04
  • Thanks for that Thomas, but what I can't understand is the exception argument must be classcast exception input stream can't be converted to fileinputstream but instead it is returning. java.lang.ClassCastException: com.jcraft.jsch.ChannelSftp$2 cannot be cast to java.io.FileInputStream – Mallikarjun Rao Nov 28 '18 at 18:21
  • That exception message only means that `Channel.getInputStream()` creates and returns an anonymous subclass of `InputStream` which is identified by `com.jcraft.jsch.ChannelSftp$2`. The class is defined and instantiated at https://github.com/rtyley/jsch/blob/master/src/com/jcraft/jsch/ChannelSftp.java#L1044 – Thomas Kläger Nov 28 '18 at 19:25
  • Thanks Thomas, I've got what I'm expecting for. Thanks for sharing the git link – Mallikarjun Rao Nov 29 '18 at 07:56

1 Answers1

0

You cannot convert from input stream to a FileInputStream without creating a temporal File. See: Convert InputStream into FileInputStream

If you want to read a file from remote and then write into a file:

Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp channelSftp = (ChannelSftp) channel;
try {
    InputStream inputStream = channelSftp.get(srcPath);
    File file = //...
    OutputStream outputStream = new FileOutputStream(file);
    IOUtils.copy(inputStream, outputStream);
    outputStream.close();
} finally {
    channel.disconnect();
    session.disconnect();
}

You can delete it after as in this response: How to convert InputStream to virtual File

kterry
  • 116
  • 2
  • 3