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); //读取指定行的内容 
                }
           
            } 
    }
  • 相关阅读:
    ie条件注释
    css3之图片一闪而过特效
    css帧动画之图片发亮
    css3动画
    解决ie6不兼容透明图片
    jquery实现拖拽的效果
    原生js实现拖拽弹框的效果
    C++学习笔记十之连接数据库
    C++学习笔记九之异常处理
    C++学习笔记八之STL内置算法
  • 原文地址:https://www.cnblogs.com/Ke-Me/p/13707266.html
Copyright © 2011-2022 走看看