io의 사용자 정의 InputStream

package com.laien.io;

import java.io.IOException;
import java.io.InputStream;

/**
 *    InputStream,   
 * 
 * @author Administrator
 *
 */
public class MyByteArrayInputStream extends InputStream {
	protected byte[] arr; //    
	protected int ptr = 0; //     
	protected int mark=0;//  
	
	/**
	 *     ,         
	 * @param arr
	 */
	public MyByteArrayInputStream(byte[] arr) {
		this.arr = arr;	
	}

	/**
	 *     ,    
	 */
	@Override
	public int read() throws IOException {
		//        ,   -1
		return (ptr < arr.length) ? arr[ptr++] : -1;
	}

	/**
	 *       
	 */
	@Override
	public int available() throws IOException {
		return arr.length - ptr;
	}
	
	@Override
	public void close() throws IOException {
		ptr = arr.length;
	}
	/**
	 *   , reset  
	 */
	@Override
	public synchronized void mark(int readlimit) {
		this.mark = readlimit;
	}
	
	@Override
	public synchronized void reset() throws IOException {
		if (this.mark<0 || this.mark >= arr.length) {
			throw new IOException("    ");
		}
		
		ptr = mark;//      mark  ,        
	}
	/**
	 *      
	 */
	@Override
	public int read(byte[] b, int off, int len) throws IOException {
		if (ptr >= arr.length || len <0) {
			//    
			return -1;
		}
		
		if (len == 0) {
			return 0;
		}
		
		//                len   ,     
		len = available() < len ? available() : len;
		
		System.arraycopy(arr, ptr, b, off, len);
		
		ptr += len;
		//       
		return len;
	}
	
	public static void main(String[] args) throws IOException {
		//  
		
		byte[] source = new byte[10];
		for (int i=0; i<source.length; i++) {
			source[i] = (byte)i;
		}
		
		MyByteArrayInputStream mis = new MyByteArrayInputStream(source);
		
		byte[] buff = new byte[4];	//
		int len =0;
		while(-1 != (len = mis.read(buff, 0, buff.length))) {
			for (int i=0; i<len; i++) {
				System.out.print(buff[i]);
			}
			System.out.println();
		}
		
	}
	
	
}

좋은 웹페이지 즐겨찾기