Example & Tutorial understanding programming in easy ways.

How to count number of characters in a file in java

A file handling program to count number of characters in a file in Java: 

import java.io.*;

class countChartest

{

public static void main(String[] args) throws IOException    {

File f = new File(args[0]);

FileOutputStream fos = new FileOutputStream(f);

for (int i=0;i<5;i++ )

{

fos.write((int)(Math.random()*4));  }

fos.close();

FileInputStream fis = new FileInputStream(f);

int ch;

int c[] = newint[5];

for (int i=0;ilength ;i++ )    {

c[i]=0;

}

while((ch=fis.read())!=-1) {

switch (ch)

{

case 0:

c[0]=c[0]+1;

break;

case 1:

c[1]=c[1]+1;

break;

case 2:

c[2]=c[2]+1;

break;

case 3:

c[3]=c[3]+1;

break;

case 4:

c[4]=c[4]+1;

break;      }

System.out.println(ch);}

System.out.println("\n\n\nCounting of Characters are\n");

for (int i=0;ilength ;i++ )  {

System.out.println("count for "+i+" : " +c[i]);     }

fis.close();

}}

Read More →