

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Questions & Answers
- 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?
- C# program to Count words in a given string
- Python 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
- Python Program to Calculate the Number of Words and the Number of Characters Present in a String
- Finding the number of words in a string JavaScript
- Java Program to Print all unique words of a String
- C program to count characters, lines and number of words in a file
- How to count the number characters in a Java string?
- Count the Number of matching characters in a pair of Java string
- Python Program to Count Number of Lowercase Characters in a String
Advertisements