1 /* 2 * Copyright (c) 2011 David Kocher. All rights reserved. 3 * Please refer to the LICENSE.txt for licensing details. 4 */ 5 package ch.ethz.ssh2; 6 7 import java.io.IOException; 8 import java.io.InputStream; 9 10 /** 11 * @version $Id:$ 12 */ 13 public class SFTPInputStream extends InputStream 14 { 15 16 private SFTPv3FileHandle handle; 17 18 /** 19 * Offset (in bytes) in the file to read 20 */ 21 private long readOffset = 0; 22 SFTPInputStream(SFTPv3FileHandle handle)23 public SFTPInputStream(SFTPv3FileHandle handle) { 24 this.handle = handle; 25 } 26 27 /** 28 * Reads up to <code>len</code> bytes of data from the input stream into 29 * an array of bytes. An attempt is made to read as many as 30 * <code>len</code> bytes, but a smaller number may be read, possibly 31 * zero. The number of bytes actually read is returned as an integer. 32 * 33 * @see SFTPv3Client#read(SFTPv3FileHandle,long,byte[],int,int) 34 */ 35 @Override read(byte[] buffer, int offset, int len)36 public int read(byte[] buffer, int offset, int len) throws IOException 37 { 38 int read = handle.getClient().read(handle, readOffset, buffer, offset, len); 39 if(read > 0) { 40 readOffset += read; 41 } 42 return read; 43 } 44 45 /** 46 * Reads the next byte of data from the input stream. The value byte is 47 * returned as an <code>int</code> in the range <code>0</code> to 48 * <code>255</code>. If no byte is available because the end of the stream 49 * has been reached, the value <code>-1</code> is returned. This method 50 * blocks until input data is available, the end of the stream is detected, 51 * or an exception is thrown. 52 * <p/> 53 * <p> A subclass must provide an implementation of this method. 54 * 55 * @return the next byte of data, or <code>-1</code> if the end of the 56 * stream is reached. 57 * @throws IOException if an I/O error occurs. 58 */ 59 @Override read()60 public int read() throws IOException { 61 byte[] buffer = new byte[1]; 62 int read = handle.getClient().read(handle, readOffset, buffer, 0, 1); 63 if(read > 0) { 64 readOffset += read; 65 } 66 return read; 67 } 68 69 /** 70 * Skips over and discards <code>n</code> bytes of data from this input 71 * stream. 72 * 73 * @param n the number of bytes to be skipped. 74 * @return the actual number of bytes skipped. 75 */ 76 @Override skip(long n)77 public long skip(long n) { 78 readOffset += n; 79 return n; 80 } 81 82 @Override close()83 public void close() throws IOException { 84 handle.getClient().closeFile(handle); 85 } 86 }