Class ByteOrderDataInStream

 1 /*
 2  * Copyright (c) 2016 Vivid Solutions.
 3  *
 4  * All rights reserved. This program and the accompanying materials
 5  * are made available under the terms of the Eclipse Public License 2.0
 6  * and Eclipse Distribution License v. 1.0 which accompanies this distribution.
 7  * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v20.html
 8  * and the Eclipse Distribution License is available at
 9  *
10  * http://www.eclipse.org/org/documents/edl-v10.php.
11  */
12 package org.locationtech.jts.io;
13  
14 import java.io.IOException;
15  
16 /**
17  * Allows reading a stream of Java primitive datatypes from an underlying
18  * {@link InStream},
19  * with the representation being in either common byte ordering.
20  */
21 public class ByteOrderDataInStream
22 {
23   private int byteOrder = ByteOrderValues.BIG_ENDIAN;
24   private InStream stream;
25   // buffers to hold primitive datatypes
26   private byte[] buf1 = new byte[1];
27   private byte[] buf4 = new byte[4];
28   private byte[] buf8 = new byte[8];
29  
30   public ByteOrderDataInStream()
31   {
32     this.stream = null;
33   }
34  
35   public ByteOrderDataInStream(InStream stream)
36   {
37     this.stream = stream;
38   }
39  
40   /**
41    * Allows a single ByteOrderDataInStream to be reused
42    * on multiple InStreams.
43    *
44    * @param stream
45    */
46   public void setInStream(InStream stream)
47   {
48     this.stream = stream;
49   }
50   public void setOrder(int byteOrder)
51   {
52     this.byteOrder = byteOrder;
53   }
54  
55   /**
56    * Reads a byte value
57    *
58    * @return the byte read
59    */
60   public byte readByte()
61       throws IOException
62   {
63     stream.read(buf1);
64     return buf1[0];
65   }
66  
67   public int readInt()
68     throws IOException
69   {
70     stream.read(buf4);
71     return ByteOrderValues.getInt(buf4, byteOrder);
72   }
73   public long readLong()
74     throws IOException
75   {
76     stream.read(buf8);
77     return ByteOrderValues.getLong(buf8, byteOrder);
78   }
79  
80   public double readDouble()
81     throws IOException
82   {
83     stream.read(buf8);
84     return ByteOrderValues.getDouble(buf8, byteOrder);
85   }
86  
87 }
88