示例#1
0
  /**
   * Replaces any empty tokens by a null token. Eg if the given delimiter
   * is ; the row
   * <P><PRE>data1;data2;;data4;
   *
   * <P>will be transformed to
   *
   * <P>data1;data2;\0;data4;\0
   *
   * @param fileRow The row to repace tokens on.
   * @param fieldDelimiter The field delimiter.
   * @return A "fixed" version of the given row.
   */
  public static String replaceEmptyTokens(String fileRow, Character fieldDelimiter) {
    // Define the empty token and the null token
    String aEmptyToken = fieldDelimiter.toString() + fieldDelimiter.toString();
    String aNullToken = fieldDelimiter.toString() + "\0" + fieldDelimiter.toString();

    // If last token is empty (ie, last char is the field delimiter),
    // append a null char at the end of the row
    if (fileRow.substring(fileRow.length() - 1).equalsIgnoreCase(fieldDelimiter.toString())) {
      fileRow = fileRow + "\0";
    }

    // Copy data to a buffer so it can be modified. Then find the
    // position of the first empty token
    StringBuffer fileRowAsBuffer = new StringBuffer(fileRow);
    int aTokenPos = fileRow.indexOf(aEmptyToken);

    // While there are empty tokens
    while (aTokenPos > -1) {
      // Replace the empty token with a null token
      fileRowAsBuffer.replace(aTokenPos, aTokenPos + 2, aNullToken);

      // Copyt data back to string and look for more empty tokens
      fileRow = fileRowAsBuffer.toString();
      aTokenPos = fileRow.indexOf(aEmptyToken);
    }
    return fileRow;
  }
示例#2
0
  /**
   * Count the number of columns on the given row. Columns are separated by the given fieldDelimiter
   * character
   *
   * @param fileRow The row to count column on.
   * @param fieldDelimiter The filed delimiter.
   * @return The number of columns found on the row.
   */
  public static int columnsOnRow(String fileRow, Character fieldDelimiter) {
    StringTokenizer aTokenizer = new StringTokenizer(fileRow, fieldDelimiter.toString(), false);

    return aTokenizer.countTokens();
  }