- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to count the number of words in a String
Create a FileInputStream object by passing the required file (object) as a parameter to its constructor. Read the contents of the file using the read() method into a byte array. Instantiate a String class by passing the byte array to its constructor. Using split() method read the words of the String to an array.
Create an integer variable, initialize it with 0, int the for loop for each element of the string array increment the count.
Example
import java.io.File; import java.io.FileInputStream; public class Sample { public static void main(String args[]) throws Exception { int count =0; File file = new File("data"); FileInputStream fis = new FileInputStream(file); byte[] bytesArray = new byte[(int)file.length()]; fis.read(bytesArray); String s = new String(bytesArray); String [] data = s.split(" "); for (int i=0; i<data.length; i++){ count++; } System.out.println("Number of characters in the given file are " +count); } }
Output
Number of characters in the given String are 4
- Related Articles
- C# program to count the number of words in a string
- Java program to count words in a given string
- How to count the number of words in a string in R?
- Python program to Count words in a given string?
- C# program to Count words in a given string
- How to count a number of words in given string in JavaScript?
- How to count the number of words in a text file using Java?
- Python Program to Count the Frequency of Words Appearing in a String Using a Dictionary
- C program to count characters, lines and number of words in a file
- Java Program to Print all unique words of a String
- Python Program to Calculate the Number of Words and the Number of Characters Present in a String
- How to count the number characters in a Java string?
- Python program to count the number of spaces in string
- Java Program to count letters in a String
- Java Program to count vowels in a string

Advertisements