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
Here is the plain java code to read fixedwidth file:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class FixedWidth {
public static void main(String[] args) throws FileNotFoundException, IOException {
// String S1="NHJAMES TURNER M123-45-67890004224345";
String FixedLengths = "2,15,15,1,11,10";
List items = Arrays.asList(FixedLengths.split("\\s*,\\s*"));
File file = new File("src/sample.txt");
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line1;
while ((line1 = br.readLine()) != null) {
// process the line.
int n = 0;
String line = "";
for (String i : items) {
// System.out.println("Before"+n);
if (i == items.get(items.size() - 1)) {
line = line + line1.substring(n, n + Integer.parseInt(i)).trim();
} else {
line = line + line1.substring(n, n + Integer.parseInt(i)).trim() + ",";
}
// System.out.println(
// S1.substring(n,n+Integer.parseInt(i)));
n = n + Integer.parseInt(i);
// System.out.println("After"+n);
}
System.out.println(line);
}
}
}
}