Text and Binary Files
Random-access files
Fixed-length strings
Random access files are often used to process files of records. For convenience, fixed-length records are used in random access files so that a record can be located easily. A record consists of a fixed number of fields. A field can be a string or a primitive data type. A string in a fixed-length record has a maximum size. If a string is smaller than the maximum size, the rest of the string is padded with blanks.
How to read and write fixed-length strings
- When you write strings to a random-access file, you need to write fixed-length strings.
- That way, the length of the strings won't vary from one record to another, and all of the record lengths in the file will be the same.
- You can create a class that contains static methods to write and read fixed-length strings.
A class that writes and reads fixed-length strings
import java.io.*; public class IOStringUtils { public static void writeFixedString( DataOutput out, int length, String s) throws IOException { for (int i = 0; i < length; i++) { if (i < s.length()) out.writeChar(s.charAt(i)); // write char else out.writeChar(0); // write unicode zero } } public static String getFixedString( DataInput in, int length) throws IOException { StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { char c = in.readChar(); // if char is not Unicode zero add to string if (c != 0) sb.append(c); } return sb.toString(); } }