Java: Get each line of data of a text string

First, define an entity, which contains two attributes: line number and content;

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;

}

Just call the following method:

    /**
     * 将文本字符串转化为每行字符串
     *
     * @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;
    }

Test code:

Test results:

 

Guess you like

Origin blog.csdn.net/sunnyzyq/article/details/125723387