Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to count words and get basic info from a file with Java

In this article we will learn how to make 3 different file operations with Java as creating and deleting files, counting words and get some informations from a file.

This article will teach you real time file operations which are needed frequently by programmers e.g. counting words in a file, etc.

Here we are going to learn :

  1. Count number of words in a given file
  2. Determining general information on file
  3. Creating and deleting files

First we assume that we have an input file which has following contents

This is Anurag Jain
My username is csanuragjain
I like writing Article
Mrbool is great place to learn.

Now we will discuss to count number of words in file.

Listing 1: Count number of words

import java.io.BufferedReader;
import java.io.FileReader;

public class CountWord 
{
	public static void main(String args[])
	{
		CountWord s=new CountWord();
		try
		{
			s.start();
		}
		catch(Exception e)
		{
			System.out.print("Some problem occured");
		}
	}
	public void start() throws Exception
	{
		FileReader fr=null;
		BufferedReader br=null;
		try
		{
			fr=new FileReader("out.txt");
			br=new BufferedReader(fr);
			String line=br.readLine();
			int totword=0;
			while(line!=null)
			{
				String a[]=line.split(" ");
				for(int i=0;i<a.length;i++)
				{
				if(a[i].length()>0)
				totword+=1;
				}
				line=br.readLine();
				
				
			}
			System.out.print("Total number of words"+totword);
			br.close();
		}
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("error"+e.getMessage());
		}
		finally
		{
		br.close();
		fr.close();
		}
	}
}
 

Here:

  1. We include BufferedReader and FileReader so that we can read the input file
  2. We make a new class and then in the main method of this new class we call the start method of this class
  3. Now in the start method we define objects of BufferedReader and FileReader and pass the file to be read as an argument
  4. We read the first line of the input file and store that in variable called line.Also we define another variable totwords which will count the total number of words in the input file
  5. Now we make a loop which reads the input file fully
  6. Inside the loop we split the line read from the input file using the split method.We split the line when a space is found.We check whether the split text is having some length so that we make sure its not counting a space again.This will give us a set of all words.
  7. Similarly we move to next line and perform same operation similarly
  8. After that we display total number of words and display on console
  9. We put code inside try-catch so that exception are handled with care

Now we will learn how to obtain basic information of a file on your computer

Listing 2: Retrieve Basic information of file

import java.io.File;
public class Fileinfo 
{
	public static void main(String args[])
	{
		Fileinfo s=new Fileinfo();
			s.start();
	}
	public void start()
	{

		try
		{
			File f=new File("source.pdf");
			
			System.out.println("Path of file is :"+f.getAbsolutePath());
			System.out.println("Name of file is :"+f.getName());
			System.out.println("Size of file is :"+f.length()/(1024)+"KB");
		}
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("error"+e.getMessage());
		}
	}
}

Here:

  1. We import file so that we may perform operation on file
  2. We make a class and also a main method which calls the start method of this class
  3. In start method we make a file object which point to our file
  4. Now we can use the several attribute of File to accomplish our task
  5. We obtain the path of the file by making use of getAbsolutePath method.This will give the location of file on the computer
  6. We determine the name of file by using the getName method.
  7. We determine the size of file using the length method and we divide it by 1024 so that it gets converted to Kb.Further dividing by 1024 give result in MB
  8. This is kept inside try-catch so that exception are caught properly

Now we learn how to enhance the previous program

Listing 3: Creating, deleting and determining

import java.io.File;
public class Fileinfo 
{
	public static void main(String args[])
	{
		Fileinfo s=new Fileinfo();
			s.start();
	}
	public void start()
	{

		try
		{
			File f=new File("source.pdf");
			f.createNewFile();
			f.deleteOnExit();
			File f2=new File("F:\\Wallpaper\\new");
			f2.mkdirs();
			if(f2.isDirectory())
				System.out.println("Directory");
			else
				System.out.println("File");
		}
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("error"+e.getMessage());
		}
	}
}
 

Here,

  1. Like we did earlier we make class, main method and a start method
  2. For first case we make a file object which is pointing to a file which may or may not exist
  3. Now to create this file we use the method createNewFile() which create the file if it does not exist. It return Boolean value telling if the operation was success or not
  4. We can delete this file when we exit the program by using deleteonexit function
  5. Now we take another case where we made a file point to a directory
  6. Now we may use mkdirs to make the given directory in case it does not exist.
  7. In case we don’t know whether the argument passed to File object is directory or File we may use the isDirectory or isFile method.
  8. This is placed under try catch for proper exception handling

This is all for today’s article. Hope you liked it. See you next time with some more interesting articles



My main area of specialization is Java and J2EE. I have worked on many international projects like Recorders,Websites,Crawlers etc.Also i am an Oracle Certified java professional as well as DB2 certified

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login