1
votes

I am tasked with writing some Java to read data from a DB2 table and write into a file in a fixed with format that can be input to a Cobol program. The Cobol layout looks like so

01 PERSON
   10 FIRST-NAME PIC X(10)   (i.e 10 bytes fixed width)
   10 LAST-NAME  PIC X(20)   (i.e 20 bytes fixed width)
   10 MIDDLE-INITIAL PIC X(1)

In Java the fields are available to me as Strings. Using the docs I came up with something like this

class Person {
    private String firstName;
    private String lastName;
    private String middleInitial;

    Person(String inFirstName, String inLastName, String inMiddleInitial){
        this.firstName = inFirstName;
        this.lastName = inLastName;
        this.middleInitial = inMiddleInitial;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String getMiddleInitial() {
        return middleInitial;
    }

}

and then in main, I had these lines of code

    st = new ST("$p.firstName$ $p.lastName$ $p.middleInitial$", '$', '$');
    st.add("p", new Person("Ethelred", "TheUnready", "X"));
    System.out.println(st.render());

Executing produces this result

Ethelred TheUnready X

What should I do to ensure the output looks like so

Ethelred  TheUnready         X

while a name like John Q Smith would like so

John      Smith              Q

Thanks!

1

1 Answers

2
votes

You could do something like

spaces = "                                                         "
outLine =   (firstName + spaces).substring(0,10)
          + (lastName + spaces).substring(0,20) 
          +  middleInitial;

There are a number of packages for writing Fixed width files from java (have a search of Sourceforge).

There are even a few packages that can use a Cobol Copybook to read/write the file:

These packages are an overkill in this case but are useful if the copybook is more complicated.


disclaimer I wrote JRecord.