Here's something I whipped up in about 30 minutes. Feel free to throw tomatoes at it.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class TBLToCSV
{
private final File input;
private final File output;
private final Map<String, Map<String, String>> chart;
private final Set<String> labels;
public TBLToCSV(File input, File output)
{
this.input = input;
this.output = output;
this.chart = new HashMap<String, Map<String, String>>();
this.labels = new LinkedHashSet<String>();
}
public void process() throws IOException
{
List<String> lines = readTextFileLines(input);
String currentName = null;
boolean foundShipClasses = false;
// generate chart
for (String line: lines)
{
line = line.trim();
if (line.equals("#Ship Classes"))
foundShipClasses = true;
if (!foundShipClasses)
continue;
if (line.startsWith("$Name:"))
{
currentName = line.substring(6).trim();
chart.put(currentName, new HashMap<String, String>());
}
String firstPart = null;
String secondPart = null;
if (line.startsWith("$") || line.startsWith("+"))
{
int colonPos = line.indexOf(":");
if (colonPos >= 0)
{
firstPart = line.substring(0, colonPos + 1).trim();
secondPart = line.substring(colonPos + 1).trim();
// truncate comments
int commentpos = secondPart.indexOf(";");
if (commentpos >= 0)
secondPart = secondPart.substring(0, commentpos).trim();
// avoid errors in CSV!
if (secondPart.contains(","))
secondPart = secondPart.replace(',', '\'');
}
}
if (firstPart == null || secondPart == null)
continue;
labels.add(firstPart);
chart.get(currentName).put(firstPart, secondPart);
}
// save chart to CSV
BufferedWriter writer = new BufferedWriter(new FileWriter(output));
String header = "";
for (String label: labels)
header += (label + ",");
writer.write(header + "\n");
for (Map.Entry<String, Map<String, String>> entry: chart.entrySet())
{
String line = "";
for (String label: labels)
line += (entry.getValue().get(label) + ",");
writer.write(line + "\n");
}
writer.close();
}
public static void main(String[] args) throws IOException
{
TBLToCSV app = new TBLToCSV(new File("C:\\temp\\ships.tbl"), new File("C:\\temp\\output.csv"));
app.process();
}
public static boolean nullSafeEquals(Object obj1, Object obj2)
{
if (obj1 == null && obj2 == null)
return true;
if (obj1 == null || obj2 == null)
return false;
return obj1.equals(obj2);
}
public static List<String> readTextFileLines(File file)
{
String str;
List<String> lines = new ArrayList<String>();
try
{
BufferedReader reader = new BufferedReader(new FileReader(file));
while ((str = reader.readLine()) != null)
lines.add(str);
reader.close();
}
catch (IOException ioe)
{
lines.clear();
}
return lines;
}
}