my aim was to create a Method which pick up any file which is separated by some char and parse out the fields (columns) the user needs and write it into another CSV file. The Jdoc is German im Sorry for that! Here is the code:
/**
* Erstellt von einer beliebigen Datei über einen Seperator eine CSV Datei und
* filtert die Felder raus die es zu suchen gilt
*
*
* @param sourcePath Vollqualifizierter Quellpfad
* @param sourceSeperator Seperator für die Quelldatei
* @param destinationPath Vollqualifizierter Zielpfad
* @param destinationSeperator Seperator für die Zieldatei
* @param fields Felder die in die CSV Datei geschrieben werden sollen
* @throws FileNotFoundException
* @throws IOException
*/
private void createCSVFile(String sourcePath, char sourceSeperator, String destinationPath, char destinationSeperator, Set<String> fields) throws FileNotFoundException, IOException
{
CSVReader reader = new CSVReader(new FileReader(sourcePath), sourceSeperator);
FileWriter writer = new FileWriter(destinationPath);
String[] nextLine;
Set<Integer> validLines = new HashSet<Integer>();
int i = 0;
// TODO STWE: Schreibt leider noch 2 mal den Header ?!
while ((nextLine = reader.readNext()) != null)
{
if (i == 0)
{
int x = 0;
for (String row : nextLine)
{
if (fields.contains(row))
{
validLines.add(x);
//Write the Header
writer.append(row + destinationSeperator);
}
x++;
}
writer.append('\n');
}
if (!validLines.isEmpty())
{
for (Integer v : validLines)
{
//Write the Content
writer.append(nextLine[v] + destinationSeperator);
}
writer.append('\n');
}
i++;
}
writer.flush();
writer.close();
reader.close();
}
Maybe you've got an easier way to do this.
Node: im using the au.com.bytecode.opencsv.CSVReader for my propose.