-3

I’m reading flat files in java with fixed length I’m new to this can anyone help me out how to do fixed length reader ?

Kalpesh Z
  • 3
  • 1
  • 4
  • 1
    Binary data or text? A FileInputStream with a fixed sized `byte[]` would be a starting point. – Joop Eggen Mar 06 '19 at 15:38
  • 2
    Welcome to StackOverflow. This is a question-and-answer site. It is not a "help" site, because that would require a different format, not "question-and-answer". Please read [why "can someone help me" not a real question](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question). Please do some research, create a program, and if you have any specific, answerable questions about it, you are welcome to post here. – RealSkeptic Mar 06 '19 at 15:39
  • It will be text file @Joop Eggen – Kalpesh Z Mar 08 '19 at 03:04

1 Answers1

1

When it is a text file, with fixed length lines, a normal reader suffices.

This assumes that there is a newline at the end of each record.

List<MyRecord> result = new ArrayList<>();

Path file = Paths.get("C:/Import/20190308.txt");
Charset charset = Charset.defaultCharset();

Files.lines(path, charset)
    .filter(line -> line.length() != 142)
    .forEach(line -> {
        MyRecord record = new MyRecord();
        record.id = Long.parseLong(line.substring(0, 10).trim());
        record.name = line.substring(10, 50).trim();
        record.age = Integer.parseInt(line.substring(50, 53).trim());
        ...
        result.add(record);
    });

The String.trim() removing the padding spaces before ("Mary ") and after (" 89"). The String.substring(position, nextPosition) picking the fixed field.

The read line is without newline character(s) - \r\n or \n in general. There is a check on the line length (here 142). This is the length in chars, but most likely is the length in bytes too, as fixed length records probably are in a single byte charset.


For some custom class MyRecord mirroring a CSV line:

public class MyRecord {
    public long id;
    public String name;
    public int age;
    ...
}
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138