-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFixedLengthStringIO.java
More file actions
24 lines (24 loc) · 992 Bytes
/
FixedLengthStringIO.java
File metadata and controls
24 lines (24 loc) · 992 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.io.*;
public class FixedLengthStringIO
{ /** Read fixed number of characters from a DataInput stream */
public static String readFixedLengthString(int size, DataInput in)
throws IOException
{ char[] chars = new char[size]; // Declare an array of characters
// Read fixed number of characters to the array
for (int i = 0; i < size; i++)
chars[i] = in.readChar();
return new String(chars);
}
/** Write fixed number of characters to a DataOutput stream */
public static void writeFixedLengthString(String s, int size,
DataOutput out) throws IOException
{ char[] chars = new char[size];
// Fill in string with characters
s.getChars(0, Math.min(s.length(), size), chars, 0);
// Fill in blank characters in the rest of the array
for (int i = s.length(); i < size; i++)
chars[i] = ' ';
// Create and write a new string padded with blank characters
out.writeChars(new String(chars));
}
}