Announcement Announcement Module
Collapse
No announcement yet.
Reading Binary file Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Reading Binary file

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

  • #2
    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.

    Comment

    Working...
    X