将 prn 文件解析为 Html 表

我必须将 .prn 文件解析为 HTML 表。

我对几列有问题 - 列之间只有一个空格 - 我不能使用多个空格作为分隔符。另外,两个段之间的列名是一个空格,但它应该被视为一条记录。我怎样才能正确解析它?


斯蒂芬大帝
浏览 132回答 1
1回答

繁花如伊

您可以使用自定义的 Split 方法,该方法会根据数据列宽度拆分每个 PRN 文件行,然后在读入时对拆分数据执行您喜欢的操作:该方法可能看起来像这样:public static String[] splitStringToChunks(String inputString, int... chunkSizes) {&nbsp; &nbsp; List<String> list = new ArrayList<>();&nbsp; &nbsp; int chunkStart = 0, chunkEnd = 0;&nbsp; &nbsp; for (int length : chunkSizes) {&nbsp; &nbsp; &nbsp; &nbsp; chunkStart = chunkEnd;&nbsp; &nbsp; &nbsp; &nbsp; chunkEnd = chunkStart + length;&nbsp; &nbsp; &nbsp; &nbsp; String dataChunk = inputString.substring(chunkStart, chunkEnd);&nbsp; &nbsp; &nbsp; &nbsp; list.add(dataChunk.trim());&nbsp; &nbsp; }&nbsp; &nbsp; return list.toArray(new String[0]);}您可以使用类似这样的方法(正如我所说,对分割的 PRN 数据执行任何您喜欢的操作):// Try With Resources used here to auto-close BufferedReader.try (&nbsp; &nbsp; BufferedReader br = new BufferedReader(new FileReader("DataFile.prn"))) {&nbsp; &nbsp; String line;&nbsp; &nbsp; StringBuilder sb;&nbsp; &nbsp; while ((line = br.readLine()) != null) {&nbsp; &nbsp; &nbsp; &nbsp; if (line.trim().equals("")) { continue; }&nbsp; &nbsp; &nbsp; &nbsp; sb = new StringBuilder();&nbsp; &nbsp; &nbsp; &nbsp; // Method called with supplied file data line and the widths of&nbsp; &nbsp; &nbsp; &nbsp; // each column as outlined within the file.&nbsp; &nbsp; &nbsp; &nbsp; String[] parts = splitStringToChunks(line, 16, 22, 9, 14, 13, 8);&nbsp; &nbsp; &nbsp; &nbsp; for (String str : parts) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sb.append(sb.toString().equals("") ? str : "; " + str);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(sb.toString());&nbsp; &nbsp; }}catch (IOException ex) {&nbsp; &nbsp; System.out.println(ex.getMessage());}通过您提供的 PRN 文件数据示例,上述示例用法将显示在控制台窗口中:Name; Address; Postcode; Phone; Credit Limit; BirthdaJohnson, John; Voorstraat 32; 3122gg; 020 3849381; 1000000; 19870101Anderson, Paul; Dorpsplein 3A; 4532 AA; 030 3458986; 10909300; 19651203Wicket, Steve; Mendelssohnstraat 54d; 3423 ba; 0313-398475; 93400; 19640603Benetar, Pat; Driehoog 3zwart; 2340 CC; 06-28938945; 54; 19640904Gibson, Mal; Vredenburg 21; 3209 DD; 06-48958986; 5450; 19781109Friendly, User; Sint Jansstraat 32; 4220 EE; 0885-291029; 6360; 19800810Smith, John; Břrkestraße 32; 87823; +44 728 889838; 989830; 19990920
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java