欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java读取按行txt文件

程序员文章站 2022-10-03 11:05:38
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; public class T { public static void main(String[] arg... ......
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class T {
    public static void main(String[] args) throws Exception{
        long startTime=System.currentTimeMillis();   //获取开始时间
        FileInputStream filestream=new FileInputStream("src/jedis/1.txt");
        byte[] b = new byte[3];
        filestream.read(b);
        String ecode="gbk";
        if (b[0] == -17 && b[1] == -69 && b[2] == -65){
            ecode="utf-8";
        }
        InputStreamReader readStream=new InputStreamReader(filestream,ecode);
        BufferedReader reader=new BufferedReader(readStream);
        
        String temp=null;
        int line=0;//行号
        while((temp=reader.readLine())!=null){
            line++;
            System.out.println(line+":"+temp);
        }
        
        long endTime=System.currentTimeMillis(); //获取结束时间
        if(readStream!=null){
            readStream.close();
        }
        if(reader!=null){
            reader.close();
        }
        System.out.println("程序运行时间: "+(endTime-startTime)/1000+"s");
    }
}