Results 1 to 2 of 2

Thread: Reading Binary file

  1. #1
    Join Date
    Jul 2010
    Location
    USA
    Posts
    43

    Question Reading Binary file

    How to read binary file in Spring batch.
    Or how to convert binary file to text

  2. #2
    Join Date
    Jan 2010
    Location
    Altan Ord
    Posts
    36

    Default

    hi,
    you can extend Reader and do something like this:

    Code:
    final public class BinaryReader extends Reader {
    	private static final Log				logger		= LogFactory.getLog(BinaryReader.class);
    	
    	private final InputStream	is;
    
    	public BinaryReader(InputStream is) {
    		this.is = is;
    	}
    	
    	private int num;
    
    	@Override
    	public int read(char[] cbuf, int off, int len) throws IOException {
    
    		byte [] bbuf = new  byte[cbuf.length]; //TODO
    		int bytesRead = is.read(bbuf, off, len);
    	
    		if (logger.isDebugEnabled()) {
    			logger.debug("cbuf.length="+cbuf.length+" off="+off+" len="+len+"  bytesRead="+bytesRead);
    		}
    		for (int i = 0; i < bytesRead; i++) {
    			cbuf[off + i] = (char) (((char) bbuf[off+i])&0x00FF);
    
    			if (logger.isDebugEnabled()) {
    				logger.debug(num+++": "+getHexString(new byte[] {(byte) (((cbuf[off + i]&0xFF00)>>8)), (byte) (cbuf[off + i]&0x00FF)}));
    			}
    		}
    		return bytesRead;
    	}
    
    	@Override
    	public void close() throws IOException {
    		is.close();
    	}
    	
    	private String getHexString(byte[] b)  {
    		  String result = "";
    		  for (int i=0; i < b.length; i++) {
    		    result +=
    		          Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
    		  }
    		  return result;
    	}

    The resutling Reader returns chars with first dummy byte (and chars are thus dummy as well). After parsing just cast chars to bytes.

    Best regards, Eugene.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •