Sunday, June 25, 2017

A very usefull java code to read the data from file and showing the details of files data along with file content

import java.io.FileInputStream;
import java.util.Scanner;

public class InputFromFile {
public static void main(String[] args) throws Exception // here i am not handling the 
// error, instead i am just declaring it 


{

// scanner object to take input from keyboard
Scanner sc = new Scanner(System.in);

System.out.print("enter a file name with full path: ");

// here i am using nextLine method, since file path may have spaces
String filePath=sc.nextLine();

// now open a file in read mode using FileInputStream class
FileInputStream fis=new FileInputStream(filePath);

// get no of bytes those can be read by read method using available method
int bytes=fis.available();

// take some variable to store the file size, no of alphabets, numeric values
// spaces and line etc
int alphaUpper=0, alphaLower=0, numeric=0, space=0, line=1;

System.out.println("showing file data ->");
// start an infinite loop
while(true)
{
// read a byte from file using read method and store byte inside a variable
int var=fis.read();

// check for end of file, as we know read method will return -1 to denote end of data
if(var==-1) { // if var has -1
break; // go out of loop
}
// check for alphabets 
if(var>='A' && var<='Z') {
alphaUpper++;
}
else if(var>='a' && var<='z') {
alphaLower++;
}
// check for numerics 
else if(var>='0' && var<='9') {
numeric++;
}
// check for spaces 
else if(var==' ') {
space++;
}
// check for lines 
else if(var=='\n') {
line++;
}
// convert the byte into ASCII character and show it on console
System.out.print((char)var);
}
System.out.println("\n---------------------------------------------");
// show the report
System.out.println("Details of file "+filePath+"->");
System.out.println("Alphabets in uppercase: "+alphaUpper);
System.out.println("Alphabets in lowercase: "+alphaLower);
System.out.println("Total Alphabets: "+(alphaLower+alphaUpper));
System.out.println("Numerics: "+numeric);
System.out.println("Spaces: "+space);
System.out.println("Lines: "+line);
System.out.println("file size: "+bytes+" bytes");
System.out.println("---------------------------------------------");

// close the file [it is a very good practice]
fis.close();

}
}

No comments:

Post a Comment