为了账号安全,请及时绑定邮箱和手机立即绑定

将 prn 文件解析为 Html 表

将 prn 文件解析为 Html 表

斯蒂芬大帝 2023-07-13 17:34:06
我必须将 .prn 文件解析为 HTML 表。我对几列有问题 - 列之间只有一个空格 - 我不能使用多个空格作为分隔符。另外,两个段之间的列名是一个空格,但它应该被视为一条记录。我怎样才能正确解析它?
查看完整描述

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


查看完整回答
反对 回复 2023-07-13
  • 1 回答
  • 0 关注
  • 93 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信