java分页读取文件
1 /** 2 * 3 * @param fileName 文件全路径 4 * @param pageNo 页数 5 * @param pageSize 每页的条数 6 * @return 7 */ 8 List<String> getLines(String fileName,int pageNo,int pageSize){ 9 File file = new File(fileName); 10 BufferedReader reader = null; 11 List<String> lines = new ArrayList<String>(); 12 try { 13 int startRow = (pageNo - 1) * pageSize + 1; //计算开始行数 14 int endRow = pageNo * pageSize; //计算结束行数 15 reader = new BufferedReader(new FileReader(file)); 16 LineNumberReader lineNumberReader = new LineNumberReader(new FileReader(file)); 17 lineNumberReader.skip(Long.MAX_VALUE); 18 int lineNumber = lineNumberReader.getLineNumber() + 1; //获取文件里面的总行数 19 if(endRow >= lineNumber){ 20 endRow = lineNumber; 21 } 22 String tempString = ""; 23 int line = 0; 24 // 一次读入一行,直到读入null为文件结束 25 while (tempString != null) { 26 line++; 27 tempString = reader.readLine(); 28 if(line >= startRow && line <= endRow) { 29 lines.add(tempString); 30 } 31 } 32 reader.close(); 33 return lines; 34 } catch (IOException e) { 35 e.printStackTrace(); 36 } finally { 37 if (reader != null) { 38 try { 39 reader.close(); 40 } catch (IOException e) { 41 e.printStackTrace(); 42 } 43 } 44 } 45 return null; 46 }