Java读取⽂件指定⾏数的数据
⽅法:创建两个⾮public类,⼀个输出本⾏内容及字符数,另⼀个确定⽂件内容的总⾏数。
代码如下:
import java.io.*;
import java.util.Scanner;
java创建文件public class ReadFile2
{
//输出本⾏内容及字符数
static void readLineVarFile(String fileName, int lineNumber) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)))
; //使⽤缓冲区的⽅法将数据读⼊到缓冲区中                String line = adLine(); //定义⾏数
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 = adLine();
}
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 = adLine(); //定义⾏数
int lines = 0;
while (s != null) //确定⾏数
{
lines++;
s = adLine();
}
reader.close();
br.close();
return lines; //返回⾏数
}
public static void main(String[] args) throws IOException
{
String fileName = "D:/"; // 读取⽂件
int totalNo = getTotalLines(fileName);  // 获取⽂件的内容的总⾏数
System.out.println("本⽂总共有:"+totalNo+ "⾏");
while(true)
{
Scanner sc=new Scanner(System.in);
int lineNumber =sc.nextInt();  // 指定读取的⾏号
readLineVarFile("D:/", lineNumber); //读取指定⾏的内容
}
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。