这是一个解决方案:
package com.foo;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Commafy {
public static final String SEPARATOR = ",";
private static void fail(String message) {
System.err.println(message);
System.exit(1);
}
private static int[] argsAsInts(String[] args) {
if (args.length < 2) {
fail("argument list of file name followed by field lengths is required");
}
int[] result = new int[args.length - 1];
for (int i = 1; i < args.length; ++i) {
try {
result[i - 1] = Integer.parseInt(args[i]);
} catch (NumberFormatException nfe) {
fail("can t convert argument "" + args[i] + "" to integer");
}
}
return result;
}
private static int[] partialSums(int[] lengths) {
int[] result = new int[lengths.length];
int start = 0;
for (int i = 0; i < lengths.length; ++i) {
result[i] = start;
start += lengths[i];
}
return result;
}
private static int[] fieldsEndAt(int[] lengths, int[] starts) {
int[] result = new int[lengths.length];
for (int i = 0; i < lengths.length; ++i) {
result[i] = starts[i] + lengths[i];
}
return result;
}
private static void process(
String fileName, int[] starts, int[] ends
) throws IOException {
BufferedReader br = new BufferedReader(
new FileReader(fileName)
);
final int MIN_LENGTH = ends[ends.length - 1];
String line = br.readLine();
while (line != null) {
if (line.length() < MIN_LENGTH) {
System.err.println("short input line "" + line +"" skipped");
} else {
StringBuilder sb = new StringBuilder();
String separate = "";
for (int i = 0; i < starts.length; ++i) {
sb.append(separate).append(line.substring(starts[i], ends[i]));
separate = SEPARATOR;
}
System.out.println(sb.toString());
}
line = br.readLine();
}
br.close();
}
public static void main(String[] args) {
int[] lengths = argsAsInts(args);
int[] starts = partialSums(lengths);
int[] ends = fieldsEndAt(lengths, starts);
try {
process(args[0], starts, ends);
} catch (IOException e) {
fail("I/O Exception while processing input");
}
}
}
给定数据文件名data/fixedlengthdata.text
,其中包含:
9483trdcvge245621jde
9483trdcvge245621jdelong
9483trdcvge245621
9483trdcvge245621jde
并运行参数:
data/fixedlengthdata.text 2 5 1 9 3
它产生输出:
94,83trd,c,vge245621,jde
94,83trd,c,vge245621,jde
short input line "9483trdcvge245621" skipped
94,83trd,c,vge245621,jde
(当然,上面的第三行输出到stderr。)