0

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.

4

2 回答 2

1

更改if (!validLines.isEmpty())else if (!validLines.isEmpty())

于 2013-06-13T08:35:33.267 回答
0

reader.readNext()不是返回单行,而是返回String[]文件当前行中以 CSV 分隔的标记的 a。在for..each循环中使用它会导致您的标题为 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++;
  }

如果您的 CSV 看起来像:

a,b,c
a,b

您将有三个标题行。

于 2013-06-13T08:38:22.337 回答