Re: Parsing a text file format
On Tue, 19 Jun 2007 08:18:32 -0700, JR wrote:
I am trying to figure out the code to read in the structure of a text
file to parse it. The way it works is the first block is the layout,
then the rest has the data so:
public class TextFileExample {
static String[] readColumns(BufferedReader in) {
LinkedList<String> columns = new LinkedList<String>();
String s;
while (!(s = in.readLine()).equals("~~~~~~")) {
columns.add(s);
}
return columns.toArray(new String[0]);
}
static String[] readRecord(BufferedReader in, String[] columns) {
String[] record = new String[columns.length];
for (int i=0;i<columns.length;i++) {
record[i] = in.readLine();
record[i] = record[i].substring(record[i].indexOf('=')+1);
}
return record;
}
public static void main(String[] args) throws Exception{
BufferedReader in = new BufferedReader(new FileReader("test.txt"));
String[] header = readColumns(in);
String s;
do {
String[] record = readRecord(in, header);
for (String key : record)
System.out.println(key);
System.out.println("------");
} while ((s = in.readLine()) != null);
}
}
This is not very good code (it assumes that at least one record exists),
but it should give you a starting point.