java 控制台实现文本查看,行数可调,回车翻页
实现如下:
public static void main(String[] args){
FileInputStream fileInputStream = null;
InputStreamReader r = null;
BufferedReader reader = null;
try {
Scanner input = new Scanner(System.in);
File file = new File("你的文件地址");
//防止乱码,使用inputStreamReader 设置编码格式 gbk 和 fileInputStream
fileInputStream = new FileInputStream(file);
r = new InputStreamReader(fileInputStream, "你需要的编码格式");
reader = new BufferedReader(r);
String in;
do {
//清屏功能 可根据控制台显示范围调整 =_=!
System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
//每一页读取3行数据 行数可调整
String writer;
for (int i = 0; i < 3; i++) {
if ((writer = reader.readLine()) != null) {
if ("".equals(writer.trim())) {
i--;//补全打印行数
continue;//跳过空行
}
System.out.println(writer);
}
}
//判断是否下一页
System.out.println("====>>");
in = input.nextLine();
} while ("".equals(in));
System.out.println("退出程序!");
}catch (IOException io){
io.printStackTrace();
}finally {
try {
if (fileInputStream != null) {
fileInputStream.close();
}
if (r != null) {
r.close();
}
if (reader != null) {
reader.close();
}
}catch (Exception e){
System.out.println("关闭资源时报错!");
e.printStackTrace();
}
}
}
新版本-增加书签、一行截取功能:
public static void main(String[] args) {
FileInputStream fs = null;
InputStreamReader r = null;
BufferedReader bf = null;
try {
//测试文件地址
fs = new FileInputStream("D:/tsxk.txt");
//中文一般编码方式UTF-8或者GBK
r = new InputStreamReader(fs, "GBK");
bf = new BufferedReader(r);
//扫描器,用于识别用户回车操作
Scanner input = new Scanner(System.in);
//书签-值为文本(书签所在行忽略)
String shuQian="第二十四章";
int maxLinLenght = 60; //每行最大长度
int len = 20; //篇幅长度
String in;
String content;
String sqLine;
//书签操作-书签所在行不读取
boolean go = true;
do {
content = bf.readLine();
if(content!=null){
go = !content.contains(shuQian);
}
}while(go);
//书签操作-结束
do {
System.out.println("\n\n\n\n\n\n\n\n\n\n");
for (int i = 0; i < len ;i++){
if((content=bf.readLine())!=null){
if("".equals(content)){
//补全一行,循环增加一次
i--;
continue;
}
//拆分过长一行
if (content.length() > maxLinLenght) {
int lineNum = content.length() / maxLinLenght + 1;
String[] str = new String[lineNum];
//循环截取数组
for (int j = 0; j < lineNum; j++) {
//判断末端下标位置
int endIndex = content.length();
if (content.length() > (j + 1) * maxLinLenght) {
endIndex = (j + 1) * maxLinLenght;
}
str[j] = content.substring(j * maxLinLenght, endIndex);
System.out.println(str[j]);
}
} else {
System.out.println(content);
}
}
}
//输入回车进入下一篇
in = input.nextLine();
}while ("".equals(in));
System.out.println("=====结束操作=====");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fs != null) {
fs.close();
}
if (r != null) {
r.close();
}
if (bf != null) {
bf.close();
}
}catch (Exception e){
System.out.println("关闭资源时报错!");
e.printStackTrace();
}
}
}