1 回答

TA貢獻2012條經驗 獲得超12個贊
您可以使用自定義的 Split 方法,該方法會根據數據列寬度拆分每個 PRN 文件行,然后在讀入時對拆分數據執行您喜歡的操作:
該方法可能看起來像這樣:
public static String[] splitStringToChunks(String inputString, int... chunkSizes) {
List<String> list = new ArrayList<>();
int chunkStart = 0, chunkEnd = 0;
for (int length : chunkSizes) {
chunkStart = chunkEnd;
chunkEnd = chunkStart + length;
String dataChunk = inputString.substring(chunkStart, chunkEnd);
list.add(dataChunk.trim());
}
return list.toArray(new String[0]);
}
您可以使用類似這樣的方法(正如我所說,對分割的 PRN 數據執行任何您喜歡的操作):
// Try With Resources used here to auto-close BufferedReader.
try (
BufferedReader br = new BufferedReader(new FileReader("DataFile.prn"))) {
String line;
StringBuilder sb;
while ((line = br.readLine()) != null) {
if (line.trim().equals("")) { continue; }
sb = new StringBuilder();
// Method called with supplied file data line and the widths of
// each column as outlined within the file.
String[] parts = splitStringToChunks(line, 16, 22, 9, 14, 13, 8);
for (String str : parts) {
sb.append(sb.toString().equals("") ? str : "; " + str);
}
System.out.println(sb.toString());
}
}
catch (IOException ex) {
System.out.println(ex.getMessage());
}
通過您提供的 PRN 文件數據示例,上述示例用法將顯示在控制臺窗口中:
Name; Address; Postcode; Phone; Credit Limit; Birthda
Johnson, John; Voorstraat 32; 3122gg; 020 3849381; 1000000; 19870101
Anderson, Paul; Dorpsplein 3A; 4532 AA; 030 3458986; 10909300; 19651203
Wicket, Steve; Mendelssohnstraat 54d; 3423 ba; 0313-398475; 93400; 19640603
Benetar, Pat; Driehoog 3zwart; 2340 CC; 06-28938945; 54; 19640904
Gibson, Mal; Vredenburg 21; 3209 DD; 06-48958986; 5450; 19781109
Friendly, User; Sint Jansstraat 32; 4220 EE; 0885-291029; 6360; 19800810
Smith, John; B?rkestra?e 32; 87823; +44 728 889838; 989830; 19990920
添加回答
舉報