Java: テキスト文字列のデータの各行を取得する

まず、行番号と内容の 2 つの属性を含むエンティティを定義します。

package com.sonar.data.vo;

import lombok.Data;

/**
 * @author Yuanqiang.Zhang
 * @since 2022/7/11
 */
@Data
public class CodeVo {

    /** 代码行数 */
    private Integer index;

    /** 源代码 */
    private String code;

}

次のメソッドを呼び出すだけです。

    /**
     * 将文本字符串转化为每行字符串
     *
     * @param s 文本代码
     * @return List<CodeVo>
     */
    public static List<CodeVo> getCodeVoList(String s) {
        if (Objects.isNull(s)) {
            return Collections.emptyList();
        }
        List<CodeVo> vos = new ArrayList<>();
        try (InputStreamReader inputStreamReader = new InputStreamReader(new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)));
             BufferedReader reader = new BufferedReader(inputStreamReader);
        ) {
            int index = 0;
            String line;
            while ((line = reader.readLine()) != null) {
                index ++;
                CodeVo vo = new CodeVo();
                vo.setCode(line);
                vo.setIndex(index);
                vos.add(vo);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return vos;
    }

テストコード:

試験結果:

 

おすすめ

転載: blog.csdn.net/sunnyzyq/article/details/125723387