JAVA 文件操作(2)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mingzhuo_126/article/details/83512328

要求:

  • 把程序调整为可以对文本文件按行进行读取,每读取一行后显示此行,并统计此行有多少字节,有多少字符并显示统计结果。最后显示总的行数。

程序:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class FileLine {
	public static void main (String args[]) throws IOException {
		File a = new File("E:\\年少有为.txt");  //Creates a new File instance 
		if (a.exists()) {  //Tests whether the file or directory denoted by this abstract pathname exists.
			System.out.println("文本:" + a.getName() + " 存在");
			
		}
		else {
			System.out.println("文本:" + a.getName() + "不存在");
			
		}
		FileReader fr = new FileReader("E:\\年少有为.txt");//Creates a new FileReader
		BufferedReader br = new BufferedReader(fr);
		//Reads text from buffering characters so as to provide for the efficient reading of characters
		String s = null;
		int i = 0;
		while((s = br.readLine())!= null) { //Reads a line of text.
			i++;
			System.out.println("第 " + i + " 行内容为:" + s);//A String containing the contents of the line
			System.out.println("第 " + i + " 行有 " + s.length() + "个字符");//Returns the length of the file 
			
		}
		System.out.println("文本一共有 " + i + " 行");
	}
}

运行结果:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/mingzhuo_126/article/details/83512328