1

I need to download a txt file from a RaspberryPi Model 3b+ over SSH and want to store another file on the android device. The problem is that the download of the file fails.

IDE: Android Studio | SSH Libary: JSch

I tried tons of different code examples that nearly all did the same. But they also didn't work. Solutions from others are working with ASync tasks. If this is the solution for my problem could someone please write a sample code for the Async Section? I really do not know how to work with that.

Heres my Code:

public static String username = "BIOGAS";
public static String host = "192.168.1.29";
public static String password = "clientOG58";
public static String targetFile = "/home/BIOGAS/ies/data.txt";
public static int port = 22;

public String download() throws Exception {
    JSch jsch = new JSch();
    Session session = null;
    String r = "No Data";
    try {
        session = jsch.getSession(username, host, port);
        session.setConfig("StrictHostKeyChecking", "no");
        session.setPassword(password);
        session.connect();

        Channel channel = session.openChannel("sftp");
        channel.connect();
        ChannelSftp sftpChannel = (ChannelSftp) channel;

        r = "" + sftpChannel.get(targetFile).toString();

        sftpChannel.exit();
        session.disconnect();
    } catch (JSchException e) {
        e.printStackTrace();
    } catch (SftpException e) {
        e.printStackTrace();
    }

    return r;
}

I expect that the file will be downloaded as a string and that string will be given back as a return statement.

Martin Prikryl
  • 147,050
  • 42
  • 335
  • 704

1 Answers1

0

InputStream.toString() does not convert the contents of the stream to string. InputStream does not implement toString() method. So you are effectively calling base Object.toString implementation, which is useless.

For a correct code, see How do I read / convert an InputStream into a String in Java?

For example, in Java 8, you can do:

String output =
    new BufferedReader(new InputStreamReader(channelSftp.get(targetFile)))
        .lines().collect(Collectors.joining("\n"));

Obligatory warning: Do not use StrictHostKeyChecking=no to blindly accept all host keys. That is a security flaw. You lose a protection against MITM attacks.

For a correct (and secure) approach, see:
How to resolve Java UnknownHostKey, while using JSch SFTP library?

Martin Prikryl
  • 147,050
  • 42
  • 335
  • 704