* @param fos
* data sink
* @throws IOException
*/
public void copyTo(final OutputStream fos) throws IOException {
final RCommandClient rcmdClient = new RCommandClient();
rcmdClient.connect(host);
try {
rcmdClient.rcommand(System.getProperty("user.name"), user,
"rcp -f " + file);
final InputStream is = rcmdClient.getInputStream();
final OutputStream os = rcmdClient.getOutputStream();
sendAck(os);
// read server response header
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
for (;;) {
final int read = is.read();
if (read < 0) {
throw new EOFException("unexpected end of stream");
}
if (read == '\n') {
break;
}
bos.write(read);
}
final String serverResponse = bos.toString("UTF-8");
// expected header for regular file: C0644 <file-size> <filename>
if (!serverResponse.isEmpty() && serverResponse.charAt(0) == 'C') {
int start = 0;
int end = serverResponse.indexOf(" ", start + 1);
start = end + 1;
end = serverResponse.indexOf(" ", start + 1);
final long filesize = Long.parseLong(serverResponse.substring(
start, end));
sendAck(os);
copyStream(is, fos, filesize);
expectAck(is);
sendAck(os);
} else {
throw new FileNotFoundException("unexpected server response: "
+ serverResponse.trim());
}
} finally {
rcmdClient.disconnect();
}
}