Stefan Höltker
Stefan Höltker

Reputation: 329

Java FileWriter Writes two headers of my CSV

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.

Upvotes: 0

Views: 2840

Answers (2)

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

reader.readNext() is not returning a single line, but a String[] that represents the CSV delimited tokens in the current line of the file. Using this in a for..each loop will cause your header to be printed once for each token in the first line of the CSV.

  for (String row : nextLine) //looping for each token in the first line
  {
      if (fields.contains(row))
      {
        validLines.add(x);
        //Write the Header
        writer.append(row + destinationSeperator);
      }
      x++;
  }

If your CSV looked like:

a,b,c
a,b

You would have three header lines.

Upvotes: 0

8192K
8192K

Reputation: 5280

Change if (!validLines.isEmpty()) to else if (!validLines.isEmpty()).

Upvotes: 1

Related Questions