用于计算文本文件中的行数、单词数、字符数和段落数的Java程序
计算字符数是必不可少的,因为几乎所有依赖用户输入的文本框都对插入的字符数有一定的限制。例如,Facebook 帖子的字符数限制为 63206 个字符。而对于 Twitter 上的推文,字符限制为 140 个字符,而 Snapchat 的每个帖子的字符限制为 80 个。
当通过 API 完成推文和 Facebook 帖子更新时,确定字符限制变得至关重要。
使用的内置函数
1. 文件(字符串路径名):
该函数位于Java.io.File包下。它通过将给定的路径名字符串转换为抽象路径名来创建一个新的 File 实例。
句法:
public File(String pathname)
参数:
pathname - A pathname string
2. FileInputStream(文件文件):
该函数位于Java.io.FileInputStream包下。它通过打开与文件系统中由 File 对象文件命名的实际文件的连接来创建 FileInputStream。
句法:
public FileInputStream(File file) throws FileNotFoundException
参数:
file - the file to be opened for reading.
抛出:
- FileNotFoundException –如果文件不存在,是目录而不是常规文件,或者由于某些其他原因无法打开读取。
- SecurityException –如果存在安全管理器并且其 checkRead 方法拒绝对文件的读取访问。
3. InputStreamReader(InputStream in):
该函数位于Java.io.InputStreamReader包下。它创建一个使用默认字符集的 InputStreamReader。
句法:
public InputStreamReader(InputStream in)
参数:
in - An InputStream
4. BufferedReader(Reader in):
该函数位于Java.io.BufferedReader包下。它创建一个使用默认大小的输入缓冲区的缓冲字符输入流。
句法:
public BufferedReader(Reader in)
参数:
in - A Reader
例子:
Java
// Java program to count the
// number of lines, words, sentences,
// characters, and whitespaces in a file
import java.io.*;
public class Test {
public static void main(String[] args)
throws IOException
{
File file = new File("C:\\Users\\hp\\Desktop\\TextReader.txt");
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
int wordCount = 0;
int characterCount = 0;
int paraCount = 0;
int whiteSpaceCount = 0;
int sentenceCount = 0;
while ((line = bufferedReader.readLine()) != null) {
if (line.equals("")) {
paraCount += 1;
}
else {
characterCount += line.length();
String words[] = line.split("\\s+");
wordCount += words.length;
whiteSpaceCount += wordCount - 1;
String sentence[] = line.split("[!?.:]+");
sentenceCount += sentence.length;
}
}
if (sentenceCount >= 1) {
paraCount++;
}
System.out.println("Total word count = "+ wordCount);
System.out.println("Total number of sentences = "+ sentenceCount);
System.out.println("Total number of characters = "+ characterCount);
System.out.println("Number of paragraphs = "+ paraCount);
System.out.println("Total number of whitespaces = "+ whiteSpaceCount);
}
}
TextReader.txt文件包含以下数据 -
Hello Geeks. My name is Nishkarsh Gandhi.
GeeksforGeeks is a Computer Science portal for geeks.
输出:
Note: This program would not run on online compilers. Please make a txt file on your system and give its path to run this program on your system.