[Java] 纯文本查看 复制代码
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
public class Test5 {
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter("temp.txt")); //创建字符输出流对象
bw.write("aaaaa\rbbbb\ncccc\r\nddddd\neeee\n"); //写入一段字符,包含回车和换行符
bw.close(); //关流
FileInputStream fis = new FileInputStream("temp.txt"); //创建字节输入流对象
int r = 0, n = 0; //定义两个变量统计回车和换行符的数量
int b; //定义变量(计数器)用于接收读取数据
while ((b = fis.read()) != -1) { //开始读取
if ('\r' == b) { //如果读到回车符,相应计数器自增
r++;
} else if('\n' == b) { //如果读到换行符,相应计数器自增
n++;
}
}
fis.close(); //关流
System.out.println("换行的个数:" + r); //打印
System.out.println("回车的个数:" + n);
}
}