【Java文本文件处理】如何在读取文本文件时添加和识别回车符

【需求】

在文本解析程序需要回车符作为结束符号,故需在读取程序中添加回车,并在解析程序中识别。

【示例文本】

夏日绝句
李清照
生当作人杰
死亦为鬼雄
至今思项羽
不肯过江东
2022年8月23日20点58分
END

【代码】

package crintxtfile;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class Test {
    public static void main(String[] args) throws Exception{
        final String txt=readTextFromFile("C:\\Users\\ufo\\Desktop\\夏日绝句.txt");
        final char[] arr=txt.toCharArray();
        
        for(int i=0;i<arr.length;i++) {
            char ch=arr[i];
            
            if(ch==13) { // 识别回车符
                System.out.println(String.format("位于%d处的字符为回车符", i));
            }
        }
    }
    
    public static String readTextFromFile(String filePath) throws Exception{
        File file=new File(filePath);
        if(!file.exists()) {
            throw new Exception(String.format("File:%s does not exist.", filePath));
        }
        
        StringBuilder sb=new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));  
        String line = null;  
        while( ( line = br.readLine() ) != null ) {
            sb.append(line+"\r");// 在行末尾主动添加回车符
        }
        br.close();  
        return sb.toString();
    }
}

【输出】

位于7处的字符为回车符
位于14处的字符为回车符
位于24处的字符为回车符
位于34处的字符为回车符
位于44处的字符为回车符
位于54处的字符为回车符
位于76处的字符为回车符
位于80处的字符为回车符

END

posted @ 2022-08-23 21:17  逆火狂飙  阅读(842)  评论(0)    收藏  举报
生当作人杰 死亦为鬼雄 至今思项羽 不肯过江东