Parsing a fixed-width formatted file in Java

后端 未结 10 2004
遥遥无期
遥遥无期 2020-11-28 10:51

I\'ve got a file from a vendor that has 115 fixed-width fields per line. How can I parse that file into the 115 fields so I can use them in my code?

My first thought

10条回答
  •  独厮守ぢ
    2020-11-28 11:27

    /*The method takes three parameters, fixed length record , length of record which will come from schema , say 10 columns and third parameter is delimiter*/
    public class Testing {
    
        public static void main(String as[]) throws InterruptedException {
    
            fixedLengthRecordProcessor("1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,10", 10, ",");
    
        }
    
        public static void fixedLengthRecordProcessor(String input, int reclength, String dilimiter) {
            String[] values = input.split(dilimiter);
            String record = "";
            int recCounter = 0;
            for (Object O : values) {
    
                if (recCounter == reclength) {
                    System.out.println(record.substring(0, record.length() - 1));// process
                                                                                    // your
                                                                                    // record
                    record = "";
                    record = record + O.toString() + ",";
                    recCounter = 1;
                } else {
    
                    record = record + O.toString() + ",";
    
                    recCounter++;
    
                }
    
            }
            System.out.println(record.substring(0, record.length() - 1)); // process
                                                                            // your
                                                                            // record
        }
    
    }
    

提交回复
热议问题