zoukankan      html  css  js  c++  java
  • Java 读取文件指定行数的数据

    方法:创建两个非public类,一个输出本行内容及字符数,另一个确定文件内容的总行数。
    代码如下:

    import java.io.*;
    import java.util.Scanner;
    public class ReadFile2 
    {      
            //输出本行内容及字符数
            static void readLineVarFile(String fileName, int lineNumber) throws IOException 
            { 
                    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName))); //使用缓冲区的方法将数据读入到缓冲区中
                    String line = reader.readLine(); //定义行数
                    if (lineNumber <= 0 || lineNumber > getTotalLines(fileName)) //确定输入的行数是否有内容
                    { 
                            System.out.println("不在文件的行数范围之内。"); 
                    } 
                    int num = 0; 
                    while (line != null)     //当行数不为空时,输出该行内容及字符数
                    { 
                            if (lineNumber == ++num) 
                            { 
                                    System.out.println("第" + lineNumber + "行: " + line+"     字符数为:"+line.length()); 
                            } 
                            line = reader.readLine(); 
                    } 
                    reader.close(); 
            } 
             
            // 文件内容的总行数    
            static int getTotalLines(String fileName) throws IOException 
            { 
                    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName))); //使用缓冲区的方法将数据读入到缓冲区中
                    LineNumberReader reader = new LineNumberReader(br); 
                    String s = reader.readLine(); //定义行数
                    int lines = 0; 
                    while (s != null) //确定行数
                    { 
                            lines++; 
                            s = reader.readLine(); 
                    } 
                    reader.close(); 
                    br.close(); 
                    return lines; //返回行数
            } 
             
            public static void main(String[] args) throws IOException 
            {                       
                String fileName = "D:/test.txt"; // 读取文件             
                int totalNo = getTotalLines(fileName);  // 获取文件的内容的总行数
                System.out.println("本文总共有:"+totalNo+ "行"); 
                while(true)
                {
                Scanner sc=new Scanner(System.in);
                int lineNumber =sc.nextInt();  // 指定读取的行号 
                readLineVarFile("D:/test.txt", lineNumber); //读取指定行的内容 
                }
           
            } 
    }
  • 相关阅读:
    return2libc实验
    Makefile初探
    Rails连接oracle配置
    ubuntu16.04配置openproject开发环境步骤
    nginx配置详解
    Ubuntu16.04安装及配置nginx
    同源策略以及绕过此限制的方法
    mysql中整数类型后面的数字,比如int(11),11代表11个字节吗?
    0412ooday01.txt=============对象和类(上)
    0426JavaSE01day02.txt=========正则、Object、包装类详解
  • 原文地址:https://www.cnblogs.com/Ke-Me/p/13707266.html
Copyright © 2011-2022 走看看