package rxxj;
import java.io.*;
public class Life {
public static void main(String[] args) {
String fileName = "D:/all/demo/day/src/rxxj/text.txt";
readFileByChars(fileName);
}
public static void readFileByChars(String fileName) {
File file = new File(fileName);
Reader reader = null;
try {
// 一次读多个字符
char[] tempchars = new char[20];
int charread = 0;
reader = new InputStreamReader(new FileInputStream(fileName));
// 读入多个字符到字符数组中,charread为一次读取字符数
while ((charread = reader.read(tempchars)) != -1) {//返回读取的字符数量,读到文本末尾返回-1,一次读取20字符
if (charread == tempchars.length) {//读取的字符数量刚好等于字符数组大小
System.out.print(tempchars);//字符数组自定义了toString()方法
} else {
for (int i = 0; i < charread; i++) { //读取的字符数量小于字符数组大小
System.out.print(tempchars[i]);
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();//关闭输入流
} catch (IOException e) {
}
}
}
}
}
一次读取指定数量的字符
最新推荐文章于 2022-06-23 09:51:58 发布