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);
}
}
}