那天以后

打印给应文件的行数

在生活或是编程中经常要打印一些指定的文件的中指定的行数,以求能够达到预想的打印效果,下面我将给大家介绍一种控制台输出的打印文件指定行数的代码:

 

代码
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
public class Test {
/**
* 读取txt内容到数组
*/
public static String[] getTxtContent(String path)
{
File f
= null;
String[] a
= null;

try {
a
= new String[100000];
f
=new File(path);
InputStreamReader read
= new InputStreamReader(new FileInputStream(f), "GBK");
BufferedReader reader
= new BufferedReader(read);
String line;
int i;

for (i = 0; i < 100000; i++)
{
if ((line = reader.readLine()) != null)
{
a[i]
= line;
}
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return a;
}

/**
* 读取指定一行内容
*
@param path
*
@param row
*
@return
*/
public String listTxtByRow1(String path,Integer row)
{
String[] s
= getTxtContent(path);
return ""+row+"行:"+s[row-1];

}

// 文件内容的总行数。
public static int getTotalLines(String path) {
int lines = 0;
try {
File file
=new File(path);
FileReader in
= new FileReader(file);
LineNumberReader reader
= new LinesNumberReader(in);
String s
= reader.readLine();

while (s != null) {
lines
++;
s
= reader.readLine();
}
reader.close();
in.close();
}
catch (Exception e) {
e.printStackTrace();
}
return lines;
}

public List<String> listTxtByRow2(String path,Integer start,Integer end)
{
List
<String> list =new ArrayList<String>();
String[] s
= getTxtContent(path);

for(int i = start;i <= end;i++)
{
list.add(s[i
-1]);
}
return list;
}
public static void main(String[] args) {
String file
="C://美好人生.txt";
Test t
= new Test();
int lineNum=20;// 打印文件的行数
List<String> list = t.listTxtByRow2(file, getTotalLines(file)-lineNum, getTotalLines(file));//取出2-5行数据
for(int i = 0;i<list.size();i++)
{
System.out.println(list.get(i));
}

}
}

 

posted on 2010-03-14 20:29  那天以后  阅读(252)  评论(0)    收藏  举报