Showing posts with label input. Show all posts
Showing posts with label input. Show all posts

Friday, August 15, 2014

Posted by Anmol Sharma
In the previous article, we discussed about two basic file handling functions in Java including searching for an existing created file in the system and creating a file using java’s inbuilt function.

In this article we will cover up the other two file handling operations which includes reading from a file and writing to a file using java’s own methods. In this program we create a file by specifying a file name, open it at the same time and add records to it as per custom format. After writing to the file, it is good practice to close it.

import java.io.*;
import java.lang.*;
import java.util.*;

public class FileHandlingTrial {

       private Formatter file;
      
              public void openFile (){ //creating & opening a file
                    
                     try{
                           file= new Formatter("New Text Document.txt"); //will be created in default workspace folder else specify a path
                     }
                    
                     catch(Exception e){
                           System.out.println("Illegal file operation");
                                 
                           }
                     }
                    
                     public void addRecords(){// writes to the created file
                           file.format("%s %s %s", "99", "MCA", "IP University");
                    
                     }
                    
                     public void closeFile(){ //good practice to close the file after use
                           file.close();
                     }
      
}


class FileHandlingTrial1 {
      
       public static void main(String[] args){
             
         FileHandlingTrial asp = new FileHandlingTrial();
        
         asp.openFile();
         asp.addRecords();
         asp.closeFile();
             
       }
}


In this last program of file handling we will read the content added by the user.
Here also we create three methods in which first opens the file, second reads the content of the file and third one finally closes the file after reading the contents.


import java.io.*;
import java.util.*;



public class FileHandlingTrial {

private Scanner file;

public void openFile(){ // to open the file
      
       try{
              file = new Scanner(new File("new.txt"));
             
             
       }
      
       catch(Exception e){
             
              System.out.println("File not found");
       }
}

public void readFile(){ // to read data from the file
      
       while(file.hasNext()){
              String a=file.next();
              String b=file.next();
              String c=file.next();
              String d=file.next();
             
              System.out.printf("%s %s %s %s\n", a, b, c, d);
             
}

}

public void closeFile(){
file.close();
}
}


class FileHandlingTrial1 {
      
       public static void main(String[] args){
             
         FileHandlingTrial asp = new FileHandlingTrial();
        
         asp.openFile();
         asp.readFile();
         asp.closeFile();
             
       }
}

Screenshot // click to open a higher resolution version





Monday, July 28, 2014

Posted by Anmol Sharma
An exception is any uncommon condition arising during execution of a program. There might be several conditions when an exception is encountered in a program but at most basic level examples of exceptions include file not found exception, dividing a number by 0, inputting a wrong data type values etc

It is necessary to handle exceptions otherwise an end user will not feel at home with the application and it is a sign of poor problem understanding. Just for example, if there is a program which accepts a string “thinkdigital” and converts it to uppercase “THINKDIGITAL” and vice a versa then there must be a facility which handles an event when a user enters a non-string input which cannot be understood by the program. This is just an example to make any layman understand about the logic of exception

In .net framework, we have System.Exception class which provides all possible exception handling facility in c#.

Any piece of code which can trigger an exception goes under the ‘try’ block, once an exception occurs, the control moves to the ‘catch’ block and handles the exception. A try block can have number of catch block depending upon different types of exceptions occurring during an operation. But always the base catch block executes first and if required child catch blocks are executed.  There is a ‘finally’ block which is optionally used for performing maintenance tasks like freeing memory, closing file stream connections etc.


// Illustration code

using System;
using System.IO; //required for file operations


class ExceptionExampleProgram
{
    public static void Main()
    {
        StreamReader streamReader = null;
        try //code which may trigger an exception comes under the try block
        {
            streamReader = new StreamReader("C:\\file\\info.txt"); //reads the content of the file specified
            Console.WriteLine(streamReader.ReadToEnd());
            streamReader.Close();

        }
        catch (FileNotFoundException Trial) // handles the exception using predefined properties in exception class or user defined message
        {

            //Console.WriteLine(FileNotFound.Message); // printing message using system defined 'Message' property
            Console.WriteLine("This program can not find the file specified {0}, Please check again", Trial.FileName); // printing user defined message to make things more clear
         
        }
        finally // to perform clean up tasks like closing connections and release memory for efficiency
        {
            if (streamReader !=null) // required as if stream reader is null then it cant be closed
            {
            streamReader.Close();
            }
            Console.WriteLine("Stream reader now closed, so is this article :P");
            Console.ReadLine();
        }
    }
}

Screenshots // click to open a higher resolution version

/* Normal Execution */

/* File Not Found Exception Handling */

/* Another type of exception which can occur if directory path is altered, 
another catch block is required for this */