views:

135

answers:

4

Hi All,

I'm creating a java program that creates a file and fills it with data in string form with each field in the record limited to a specific length.

What I think I need to do is to create a class that has a string for the data field and a length specifying the length of the string. And then somehow restrict it so that the string never exceeds this length, either by bailing, padding with whitespace (if the data input is less that the length) or truncating the end so the data fits.

My first question is if there is already a basic class that will do this, or should I just roll my own.

My second question is if I do roll my own how do I make sure when the class is constructed that the initial value of the internal String is less than the length specified, Ive read elsewhere that a constructor should return a value, but is it valid for a constructor to raise an exception?

Thanks for any help.

+2  A: 

Use printf or format

System.out.printf("\n%-5d%-20s",10,"Hello");
adatapost
+2  A: 

You can use StringUtils, which is part of Commons Lang and use the following method:

String rightPad(java.lang.String str, int size, char padChar)

like this:

String myPaddedString = StringUtils.rightPad("Sample string", 20, "*")

You can then write that to a file - take a look at Commons IO FileUtils for a neat way to write a string easily...

On your second point.. a constructor can't return a value, otherwise it would be a standard method, but it is free to raise an exception based on the parameters passed into it - IllegalArgumentException is the most appropriate in this case.

Jon
A: 

You could do something like this:

public class Field {
    // other members not shown
    int length;
    String value;

    public Field(int length, String initialValue) {
        // omitted error check for length > 0
        this.length = length;
        setValue(initialValue);
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        if (value != this.value) {
            if (value == null)
                value = "";
            if value.length() > length)
                value = value.substring(0, length);
            else
                value = String.format("%1$-" + length + "s", value);
            this.value = value;
        }
    }
}
Vinay Sajip
This is closer to what I was thinking, and im pretty sure it covers all conditions. But how would you pass back an error if it did occur?
Mark Underwood
+3  A: 

Here's my take - it meets all the requirements in your question. You'll note that I've chosen to reject illegal assignments with an IllegalArgumentException.

package com.pragmaticsoftwaredevelopment.stackoverflow;

public class FixedLengthString {
   private String string=null;
   private int length=-1;
   public FixedLengthString(int length) { 
      this.length = length; 
   }
   public void setValue (String str) {
      if (str.length() > length)
         throw new IllegalArgumentException("ERROR: Assigned string length (" + str.length() + ") exceeded given limit (" + length + ")");
      else
         this.string = str;
   }
   public String toString() {
      return String.format("%1$-" + length + "s", string);

   }
   public String getString() { 
      return toString();
   }
}


CPerkins
Exactly what I wanted. Thanks!
Mark Underwood