Menu

JRecord_Cobol2Csv

Bruce Martin

Cobol to Csv with just JRecord

Here is a simple example for converting a Single Record Type Cobol data file to CSV with just JRecord (and not CobolToCsv)

        try {
            ICobolIOBuilder iob = JRecordInterface1.COBOL
                                        .newIOBuilder(copybookName)
                                            .setFont("cp037")                                   // US EBCDIC
                                            .setFileOrganization(IFileStructureConstants.IO_FIXED_LENGTH_RECORDS);  
            AbstractLineReader reader = iob.newReader(dataFile);
            ICsvIOBuilder csvOBuilder = JRecordInterface1.CSV.newIOBuilder(",", "\"");
            IDefineCsvFields csvFields = csvOBuilder.defineFields();

            AbstractLine line = reader.read();
            if (line != null) {
                FieldIterator fieldIterator = line.getFieldIterator(0);
                for (AbstractFieldValue fv : fieldIterator) {
                    csvFields.addCsvField(fv.getFieldDetail().getName(), Type.ftChar, 0);
                }
                csvOBuilder = csvFields.endOfRecord();

                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                AbstractLineWriter csvWriter = csvOBuilder.newWriter(byteArrayOutputStream);
                while (line != null) {
                    AbstractLine csvLine = csvOBuilder.newLine();
                    int fldNum = 0;
                    for (AbstractFieldValue fv : fieldIterator) {
                        csvLine.getFieldValue(0, fldNum++).set(fv.asString());
                    }
                    csvWriter.write(csvLine);
                    line = reader.read();
                }
                csvWriter.close();
                System.out.println(byteArrayOutputStream.toString());
            }

            reader.close();

        } catch (Exception e) {
            System.out.println("~~> " + e.getMessage());
            System.out.println();

            e.printStackTrace();
        }