0

I have a file in unix directory that I need to read and display content of it to the page. I am using jcraft library in my java code. I am able to connect to Unix server and find the file but can’t read it. I found sample code to read a file but it isn’t working, it dies on the int c = in.read()line, probably stuck in the loop… I am posting my code may be you can spot a problem. If there are other(better) ways to do it I would appreciate an example. Hope my question and sample code it clear enough. Thanks all.

public String readFile(String path) throws Exception {

    ChannelExec c = (ChannelExec)session.openChannel("exec");
    OutputStream os = c.getOutputStream();
    InputStream is = c.getInputStream();
    c.setCommand("scp -f " + path); //path is something like /home/username/sample.txt
    c.connect();
    String header = readLine(is);

    int length = Integer.parseInt(header.substring(6, header.indexOf(' ', 6)));
    os.write(0);
    os.flush();

    byte[] buffer = new byte[length];
    length = is.read(buffer, 0, buffer.length);
    os.write(0);
    os.flush();

    c.disconnect();

    return new String(buffer);  
}

private String readLine(InputStream in) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    for (;;) {
        int c = in.read(); // code stops working here
        if (c == '\n') {
            return baos.toString();
        } else if (c == -1) {
            throw new IOException("End of stream");
        } else {
            baos.write(c);
        }
    }
}
JS11
  • 181
  • 3
  • 7
  • 16

2 Answers2

1

You want to look into using ChannelSftp instead of ChannelExec:

ChannelSftp channelSftp = null;
try {
    channelSftp = (ChannelSftp) session.openChannel("sftp");
    channelSftp.connect();
    is = channelSftp.get(path);
    // read the contents, etc...
} finally {
    if (channelSftp != null) {
        channelSftp.exit();
    }
}
laz
  • 28,320
  • 5
  • 53
  • 50
0

This looks alright. I am assuming it simply hangs (like you said) at the read.

[...] This method blocks until input data is available [...]

I am thinking you are having trouble establishing the channel. Is the scp possibly waiting for your password or something?


On second thought your line detection might not work. This would result in the for jumping beyond where you would want it to exit. Maybe you should also check for '\r' too.


Also somebody did something similar here: How to read JSch command output?

Community
  • 1
  • 1
zsawyer
  • 1,824
  • 17
  • 24