001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.imaging.common; 018 019import java.io.IOException; 020import java.io.PrintWriter; 021import java.io.StringWriter; 022import java.nio.ByteOrder; 023import java.util.logging.Level; 024import java.util.logging.Logger; 025 026public class BinaryFileParser { 027 028 private static final Logger LOGGER = Logger.getLogger(BinaryFileParser.class.getName()); 029 030 /** 031 * The default {@link ByteOrder} for parsers is {@link ByteOrder#BIG_ENDIAN}. 032 */ 033 private ByteOrder byteOrder = ByteOrder.BIG_ENDIAN; 034 035 /** 036 * Constructs a new instance with the default, big-endian, byte order. 037 */ 038 public BinaryFileParser() { 039 // empty 040 } 041 042 public BinaryFileParser(final ByteOrder byteOrder) { 043 this.byteOrder = byteOrder; 044 } 045 046 protected final void debugNumber(final PrintWriter pw, final String msg, final int data, final int bytes) { 047 pw.print(msg + ": " + data + " ("); 048 int byteData = data; 049 for (int i = 0; i < bytes; i++) { 050 if (i > 0) { 051 pw.print(","); 052 } 053 final int singleByte = 0xff & byteData; 054 pw.print((char) singleByte + " [" + singleByte + "]"); 055 byteData >>= 8; 056 } 057 pw.println(") [0x" + Integer.toHexString(data) + ", " + Integer.toBinaryString(data) + "]"); 058 pw.flush(); 059 } 060 061 protected final void debugNumber(final String msg, final int data, final int bytes) { 062 try (StringWriter sw = new StringWriter(); 063 PrintWriter pw = new PrintWriter(sw)) { 064 debugNumber(pw, msg, data, bytes); 065 pw.flush(); 066 sw.flush(); 067 LOGGER.fine(sw.toString()); 068 } catch (final IOException e) { 069 LOGGER.log(Level.SEVERE, e.getMessage(), e); 070 } 071 } 072 073 public ByteOrder getByteOrder() { 074 return byteOrder; 075 } 076 077 protected void setByteOrder(final ByteOrder byteOrder) { 078 this.byteOrder = byteOrder; 079 } 080}