分页读取文件内容
作者:互联网
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class PagingReadFile {
/** 记录分页次数 */
public static int sortCount = 0;
/** 每页读取的条数 */
public final static int PAGING_COUNT = 100;
/**
* 读取文件数据
*/
public static void pagingReadFileData(){
int totalCount = getTotalCount();
// 记录是否是否读到文件末尾,用于判断当最后一页数量不满足100条时也进行业务处理
int count = 0;
List<String> stringList = new ArrayList();
String temp = "";
try (BufferedReader reader =
new BufferedReader(
new InputStreamReader(
new FileInputStream(new File("D:\\Users\\Desktop\\paging.txt"))
, "UTF-8"))) {
while ((temp = reader.readLine()) != null) {
count++;
stringList.add(temp);
// 满足每页读取条数或者当最后一页数量不能满足固定条数时都进行业务处理
if (stringList.size() == PAGING_COUNT || count == totalCount) {
printFileContent(stringList);
// 处理后清空再次读取
stringList.clear();
}
}
} catch (Exception e) {
}
}
/**
* 获取数据总条数
*/
public static int getTotalCount() {
int count = 0;
try (BufferedReader reader =
new BufferedReader(
new InputStreamReader(
new FileInputStream(new File("D:\\Users\\Desktop\\paging.txt"))
, "UTF-8"))) {
while (reader.readLine() != null) {
count ++;
}
} catch (Exception e) {
}
return count;
}
/**
* 业务处理
*/
public static void printFileContent (List<String> stringList) {
System.out.println("第" + ++sortCount + "页数据:" + stringList);
}
/**
* 写入数据进行测试
*/
public static void writeDateToFile () {
try (BufferedWriter writer =
new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(new File("D:\\Users\\Desktop\\paging.txt"))
, "UTF-8"))) {
for (int i = 1; i <= 2022; i++) {
writer.append(i + "\r\n");
}
} catch (Exception e) {
}
}
}
标签:count,文件,读取,int,public,static,new,stringList,分页 来源: https://blog.csdn.net/m0_46608027/article/details/122317774