Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import junit.framework.AssertionFailedError;
- import java.io.IOException;
- import java.nio.file.*;
- import java.util.logging.Logger;
- import java.util.stream.Stream;
- public class BestWayToWriteMethod {
- private static final Logger logger = Logger.getLogger("BestWayToWriteMethod");
- private final FileSystem _fileSystem;
- public BestWayToWriteMethod() {
- this(FileSystems.getDefault());
- }
- public BestWayToWriteMethod(final FileSystem fileSystem) {
- _fileSystem = fileSystem;
- }
- public void processFile(final String fileName) throws IOException {
- class LoopVariables {
- int lineNumber = 0;
- int detailRecordCount = 0;
- boolean trailerRecordSeen = false;
- }
- final LoopVariables vars = new LoopVariables();
- try (Stream<String> stream = Files.lines(_fileSystem.getPath(fileName))) {
- stream.forEach(line -> {
- ++vars.lineNumber;
- final String recordType = line.substring(0, 2);
- if (vars.trailerRecordSeen) {
- // Not allowed to have more records after the trailer.
- throw new AssertionFailedError("Invalid record after trailer on line " + vars.lineNumber + ": " + line);
- } else if (vars.lineNumber == 1) {
- // The first record in the file must be the header record.
- if (!recordType.equals("01")) {
- throw new AssertionFailedError("First record must be a header record. Found record type '" + recordType + "' instead. Line #1 = " + line);
- }
- } else {
- switch (recordType) {
- case "01": // Out of place Header Record
- throw new AssertionFailedError("Duplicate header record found at line " + vars.lineNumber + ": " + line);
- case "02": // Detail Record
- ++vars.detailRecordCount;
- // TODO: Presumably more "detail record procesing" would be done here.
- break;
- case "99": // Trailer Record
- vars.trailerRecordSeen = true;
- final String rawRecordCount = line.substring(12, 21);
- final int recordCount = Integer.parseInt(rawRecordCount);
- if (recordCount != vars.detailRecordCount) {
- throw new AssertionFailedError("Trailer record has incorrect record count. Trailer record has " + recordCount + ". Actual detail record count " + vars.detailRecordCount + ".");
- }
- break;
- default:
- throw new AssertionFailedError("Unrecognized record type '" + recordType + "' found at line " + vars.lineNumber + ": " + line);
- }
- }
- });
- }
- }
- }
Add Comment
Please, Sign In to add comment