1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.commons.flatfile;
18
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.OutputStream;
22
23 /**
24 * Stores string representations of objects in a (fixed-length) byte array.
25 * @version $Revision: 757266 $ $Date: 2009-03-22 17:12:27 -0500 (Sun, 22 Mar 2009) $
26 */
27 public class Field extends PadJustifyFieldSupport {
28
29 private static final long serialVersionUID = 3939293448043882440L;
30
31 private Overflow overflow;
32 private byte[] buffer;
33
34 /**
35 * Create a new Field.
36 * @param size of field
37 */
38 public Field(int size) {
39 this(new byte[size]);
40 }
41
42 /**
43 * Create and initialize a new Field.
44 * @param buffer byte[] which is not copied, but used directly.
45 */
46 public Field(byte[] buffer) {
47 this.buffer = buffer;
48 }
49
50 /**
51 * {@inheritDoc}
52 */
53 public int length() {
54 return buffer.length;
55 }
56
57 /**
58 * {@inheritDoc}
59 */
60 public synchronized void readFrom(InputStream is) throws IOException {
61 is.read(buffer);
62 }
63
64 /**
65 * {@inheritDoc}
66 */
67 public synchronized void writeTo(OutputStream os) throws IOException {
68 os.write(buffer);
69 }
70
71 /**
72 * {@inheritDoc}
73 */
74 public void setValue(byte[] b) {
75 getOverflow().check(b, buffer.length);
76 super.setValue(b);
77 }
78
79 /**
80 * {@inheritDoc}
81 */
82 public byte[] getValue() {
83 return buffer;
84 }
85
86 /**
87 * {@inheritDoc}
88 */
89 public Field clone() {
90 Field result = (Field) super.clone();
91 result.buffer = new byte[buffer.length];
92 System.arraycopy(buffer, 0, result.buffer, 0, buffer.length);
93 return result;
94 }
95
96 /**
97 * Get the overflow.
98 * @return Overflow
99 */
100 public Overflow getOverflow() {
101 return overflow == null ? Overflow.ERROR : overflow;
102 }
103
104 /**
105 * Set the overflow.
106 * @param overflow Overflow
107 */
108 public void setOverflow(Overflow overflow) {
109 this.overflow = overflow;
110 }
111
112 /**
113 * {@inheritDoc}
114 */
115 protected int getPadJustifyLength() {
116 return length();
117 }
118 }