Showing posts with label Core Java. Show all posts
Showing posts with label Core Java. Show all posts

Thursday, June 04, 2015

How to solve File Not Found Exception - java.io.FileNotFoundException

In this post we will going to take a look at FileNotFoundException in Java. This exception is thrown during a failed attempt to open the file denoted by a specified path-name. Also, this exception can be thrown when an application tries to open a file for writing, but the file is read only, or the permissions of the file do not allow the file to be read by any application.

This exception extends the IOException class, which is the general class of exceptions produced by failed or interrupted I/O operations. Also, it implements the Serializable interface and finally, theFileNotFoundException exists since the first version of Java (1.0).

The FileNotFoundException in Java

The following constructors throw a FileNotFoundException when the specified filename does not exist: FileInputStream,FileOutputStream, and RandomAccessFile. These classes aim to obtain input bytes from a file in a file system, while the former class supports both reading and writing to a random access file.

The following snippet reads all the lines of a file, but if the file does not exist, a FileNotFoundException is thrown.

FileNotFoundExceptionExample.java:


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class FileNotFoundExceptionExample {
 
 private static final String filename = "input.txt";
 
 public static void main(String[] args) {
  BufferedReader rd = null;
  try {
   // Open the file for reading.
   rd = new BufferedReader(new FileReader(new File(filename)));
   
   // Read all contents of the file.
   String inputLine = null;
   while((inputLine = rd.readLine()) != null)
    System.out.println(inputLine);
  }
  catch(IOException ex) {
   System.err.println("An IOException was caught!");
   ex.printStackTrace();
  }
  finally {
   // Close the file.
   try {
    rd.close();
   }
   catch (IOException ex) {
    System.err.println("An IOException was caught!");
    ex.printStackTrace();
   }
  }
 }
}
In case the file is missing, the following output is produced: An IOException was caught!
java.io.FileNotFoundException: input.txt (No such file or directory)
 at java.io.FileInputStream.open(Native Method)
 at java.io.FileInputStream.(FileInputStream.java:146)
 at java.io.FileReader.(FileReader.java:72)
 at main.java.FileNotFoundExceptionExample.main
(FileNotFoundExceptionExample.java:16) Exception in thread "main" java.lang.NullPointerException at main.java.FileNotFoundExceptionExample.main
(FileNotFoundExceptionExample.java:30)
The following snippet tries to append a string at the end of a file. If the file does not exist, the application creates it. However, if the file cannot be created, is a directory, or the file already exists but its permissions are sufficient for changing its content, a FileNotFoundException is thrown.

FileNotFoundExceptionExample_v2.java:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileNotFoundExceptionExample_v2 {
 
 private static final String filename = "input.txt";
 
 public static void main(String[] args) {
  BufferedWriter wr = null;
  try {
   // Open the file for writing, without removing its current content.
   wr = new BufferedWriter(new FileWriter(new File(filename), true));
   
   // Write a sample string to the end of the file.
   wr.write("A sample string to be written at the end of the file!\n");
  }
  catch(IOException ex) {
   System.err.println("An IOException was caught!");
   ex.printStackTrace();
  }
  finally {
   // Close the file.
   try {
    wr.close();
   }
   catch (IOException ex) {
    System.err.println("An IOException was caught!");
    ex.printStackTrace();
   }
  }
 }
}
If the file exists and is a directory, the following exception is thrown: An IOException was caught!
java.io.FileNotFoundException: input.txt (Is a directory)
 at java.io.FileOutputStream.open(Native Method)
 at java.io.FileOutputStream.(FileOutputStream.java:221)
 at java.io.FileWriter.(FileWriter.java:107)
 at main.java.FileNotFoundExceptionExample_v2.main
       (FileNotFoundExceptionExample_v2.java:16)
Exception in thread "main" java.lang.NullPointerException
 at main.java.FileNotFoundExceptionExample_v2.main
       (FileNotFoundExceptionExample_v2.java:28)
If the file exists, but it doesn’t have the appropriate permissions for writing, the following exception is thrown: An IOException was caught!
java.io.FileNotFoundException: input.txt (Permission denied)
 at java.io.FileOutputStream.open(Native Method)
 at java.io.FileOutputStream.(FileOutputStream.java:221)
 at java.io.FileWriter.(FileWriter.java:107)
 at main.java.FileNotFoundExceptionExample_v2.main
        (FileNotFoundExceptionExample_v2.java:16)
Exception in thread "main" java.lang.NullPointerException
 at main.java.FileNotFoundExceptionExample_v2.main
        (FileNotFoundExceptionExample_v2.java:28)
 
Finally, the aforementioned exception can occur when the requested file exists, but it is already opened by another application.

How to deal with the FileNotFoundException 


  • If the message of the exception claims that there is no such file or directory, then you must verify that the specified is correct and actually points to a file or directory that exists in your system. 
  • If the message of the exception claims that permission is denied then, you must first check if the permissions of the file are correct and second, if the file is currently being used by another application. 
  • If the message of the exception claims that the specified file is a directory, then you must either alter the name of the file or delete the existing directory (if the directory is not being used by an application).

Saturday, July 26, 2014

Naming a Thread

Every Thread in a class has its own name like Thread-0, Thread – 1 and so on. We can also setthe name of Thread and get name of the Thread by two methods of Thread class as, public String getName() : return the name of the thread. public void setName(String name): set the name of the thread.

Example:

public class MyThread extends Thread{
 public void run(){
   try{
       for(int i=0;i<=5;i++){
         Thread.sleep(1000);
         System.out.println("Running thread is  = "+Thread.currentThread().getName());
       }
    }catch(InterruptedException ie){}
 }
 public static void main(String[] args){
     MyThread mt1 = new MyThread();
     MyThread mt2 = new MyThread();
     MyThread mt3 = new MyThread();
     mt1.start();
     mt2.start();
     mt3.start();
 }
}
Output: 

Running thread is  = Thread-0
Running thread is  = Thread-1
Running thread is  = Thread-2
Running thread is  = Thread-1
Running thread is  = Thread-2
Running thread is  = Thread-0
Running thread is  = Thread-2
Running thread is  = Thread-0......
Note: If you haven’t set the name of the thread the default name are Thread-0,Thread-1 so on..

public class MyThread extends Thread{
   public void run() {
        try {
            for (int i = 0; i <= 5; i++) {
                Thread.sleep(1000);
                System.out.println("Running thread is  = " + Thread.currentThread().getName();
            } // currentThread() returns current executing thread
        }
        catch (InterruptedException ie) {}
    }
    
    public static void main(String[] args){
        MyThread mt1 = new MyThread();
        MyThread mt2 = new MyThread();
        MyThread mt3 = new MyThread();
        mt1.setName("One Thread");                                                           // to set the name of the thread
        mt2.setName("Two Thread");
        mt3.setName("Three Thread");
        mt1.start();
        mt2.start();
        mt3.start();
    } 
}

Sleeping a Thread

There are two overloaded methods of sleep in Thread class. The Thread object is sleep for specified amount of time. The sleep() method is a static method of class Thread. You use it in your code to "slow a thread down" by forcing it to go into a sleep mode before coming back to runnable. Notice that the sleep() method can throw a checked InterruptedException. Typically, you wrap calls to sleep() in a try/catch.

Example:

public class MyThread extends Thread{
    public void run(){
            try{
                for(int i=0;i<=5;i++){
            Thread.sleep(1000);
            System.out.println("Running here for.."+i);
                }
            }catch(InterruptedException ie){}
    }

    public static void main(String[] args){
        MyThread mt1 = new MyThread();
        MyThread mt2 = new MyThread();
        MyThread mt3 = new MyThread();
        mt1.start();
        mt2.start();
        mt3.start();
    }
}
Output:

Running here for..0
Running here for..0
Running here for..0
Running here for..1
Running here for..1
Running here for..1
Running here for..2
Running here for..2
Running here for..2
Running here for..3
Running here for..3
Running here for..3
Running here for..4
Running here for..4
Running here for..4
Running here for..5
Running here for..5
Running here for..5

Few Points to note here,

Just keep in mind that the behaviour in the preceding output is still not guaranteed.

When a thread encounters a sleep call, it must go to sleep for at least the specified number of milliseconds (unless it is interrupted before its wake-up time, in which case it immediately throws the InterruptedException).

Just because a thread’s sleep() expires, and it wakes up, does not mean it will return to running! When a thread wakes up, it simply goes back to the runnable state. So the time specifi ed in sleep () is the minimum duration in which the thread won’t run.

Methods of Thread Class

  • public void run(): is used to perform action for a thread. 
  • public void start(): starts the execution of the thread.JVM calls the run() method on the thread. 
  • public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. 
  • public void join(): waits for a thread to die. 
  • public void join(long miliseconds): waits for a thread to die for the specified miliseconds. 
  • public int getPriority(): returns the priority of the thread. 
  • public int setPriority(int priority): changes the priority of the thread. 
  • public String getName(): returns the name of the thread. 
  • public void setName(String name): changes the name of the thread. 
  • public Thread currentThread(): returns the reference of currently executing thread. 
  • public int getId(): returns the id of the thread. 
  • public Thread.State getState(): returns the state of the thread. 
  • public boolean isAlive(): tests if the thread is alive. 
  • public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute. 
  • public void suspend(): is used to suspend the thread(depricated).
  • public void resume(): is used to resume the suspended thread(depricated). 
  • public void stop(): is used to stop the thread(depricated). 
  • public boolean isDaemon(): tests if the thread is a daemon thread. 
  • public void setDaemon(boolean b): marks the thread as daemon or user thread. 
  • public void interrupt(): interrupts the thread. 
  • public boolean isInterrupted(): tests if the thread has been interrupted. 
  • public static boolean interrupted(): tests if the current thread has been interrupted. As we have seen that to start the execution under run() method we need to start the thread. 
But what, if we start the thread twice, it will throw IllegalThreadStateException.
Example:
public class MyThread extends Thread{
public void run(){
           System.out.println("Important job goes here..");
}
public static void main(String[] args){
          MyThread mt = new MyThread();
          mt.start();
          mt.start();
       }
}
Output:

Important job goes here..
Exception in thread "main" java.lang.IllegalThreadStateException
                at java.lang.Thread.start(Thread.java:638)
                at com.test.MyThread.main(MyThread.java:19)
What if we directly calls the run() method, like
public class MyThread extends Thread{
    public void run(){
        System.out.println("Important job goes here..");
    }
  
    public static void main(String[] args){
        MyThread mt = new MyThread();
        mt.run();
    }
}
Invoking run() method directly from the main thread the call goes to the current call stack rather than beginning a new call stack.

Thread Class

Let’s understand what we are doing here, we have four constructors of Thread class,
  • Thread()
  • Thread(Runnable target)
  • Thread(Runnable target, String name)
  • Thread(String name)
If you create a thread using the no-arg constructor, the thread will call its own run() method when it's time to start working. That's exactly what you want when you extend Thread, but when you use Runnable, you need to tell the new thread to use your run()method rather than its own. The Runnable you pass to the Thread constructor is called the target or the target Runnable.

As you can see in Thread class provided by java, the run() method is define as,
public void run() {
    if (target != null) {
           target.run();// That call your class run() method
    }    
}
At this point, all we have is the plain old java object of Thread class, It is not yet a thread of execution. To get an actual thread—a new call stack—we still have to start the thread.
To start a thread we write ,

t.start();

Few points to remember:
  • When a thread has been instantiated but not started (in other words, the start() method has not been invoked on the Thread instance), the thread is said to be in the new state.
  •  At this stage, the thread is not yet considered to be alive.
  •  Once the start() method is called, the thread is considered to be alive(even though the run() method may not have actually started executing yet).
  •  A thread is considered dead (no longer alive) after the run() method completes.
  •  When start() method called , a new thread of execution starts (with a new call stack).
  • The thread moves from the new state to the runnable state.
  • When the thread gets a chance to execute, its target run() method will run.

Creating Thread


There are 2 ways : 
  • By extending a Thread class
  • By implementing runnable interface.

Defining Thread: 
  • Extending Thread class
  • Overriding run() method

Example:
public class MyThread extends Thread{
    public void run(){
        System.out.println("Important job goes here..");
    }
  
    public static void main(String[] args){
        MyThread mt = new MyThread();
        mt.start();
    }
}
Output:

Important job goes here..

If you implement Runnable, instantiation is only slightly less simple. To have code run by a separate thread, you still need a Thread instance. But rather than combining both the thread and the job (the code in the run()method) into one class, you've split it into two classes—the Thread class for the thread-specific code and your Runnable implementation class for your job-that-should-be-run-by-a thread code. 

What is Thread in Java


So what exactly is a thread? In Java, "thread" means two different things:


  •  An instance of class java.lang.Thread
  •  A thread of execution

An instance of Thread is just like an object. Like any other object in Java, it has variables and  methods, and lives and dies on the heap. But a thread of execution is an individual process (a "lightweight" process) that has its own call stack. In Java, there is one thread per call stack or, to think of it in reverse, one call stack per thread. The main() method, that starts the whole execution , runs in one thread, called the main thread.


Life Cycle of Thread (Thread State):

A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. The life cycle of a thread is maintained by JVM.

      

New : A thread begins its life cycle in the new state. It remains in this state until the start() method is called on it. It is also referred to as a born thread.

Runnable : The Thread is in runnable state when start() method is called. It will remain in the runnable state until the thread scheduler picks the thread into running state.

Running : This is the actual running state of the thread. It happens when thread scheduler chosen the thread from runnable state.

Blocked : This is the state when the thread is alive but not in the running state. When it resume it directly goes to the runnable state not in running state.

Terminated: thread is terminated or in dead state. This state arrives when run() method exits or completed the task.

Thread Scheduler :


  •  The thread scheduler is the part of the JVM,that decides which thread should run at any given moment, and also takes threads out of the run state.
  •  And it's the thread scheduler that decides which thread of all that are eligible(runnable state) will actually run.
  •  Any thread in the runnable state can be chosen by the scheduler to be the one and only running thread.
  • The order in which runnable threads are chosen to run is not guaranteed.

Multithreading


Thread:

A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution. It shares the memory area of process. A single process might contain multiple threads . All threads within a process share the same state and same memory space, and can communicate with each other directly, because they share the same variables.

Multithreading:

To understand multithreading, we need to understand first the difference between process and Thread. A process is a program in execution. A process may be divided into a number of independent units known as threads. A thread is a dispatchable unit of work. Threads are light-weight processes within a process. A process is a collection of one or more threads and associated system resources.



    
Multitasking :

Multitasking of two or more processes is known as process-based multitasking. Multitasking of two or more threads is known as thread-based multitasking. Process-based multitasking is totally controlled by the operating system. But thread-based multitasking can be controlled by the programmer to some extent in a program.


Now, Multithreading is a process of executing multiple threads simultaneously, or you can say, Multithreading is a technique that allows a program or a process to execute many tasks concurrently (at the same time and parallel). Java provides built-in support for multithreaded programming.                

Advantages of multithreading over multiprocessing :

  • Reduces the computation time.
  • Improves performance of an application.
  • Threads share the same address space so it saves the memory.
  • Context switching between threads is usually less expensive than between processes.
  • Cost of communication between threads is relatively low.

Friday, July 25, 2014

Nested Class

Nested Classes : 
One of the advantageous features of Java is the ability to define nested classes, i.e. classes within classes. In java classes are either top-level-classes (classed defined directly within a package) or nested classes (classes defined within top-level-classes). We use nested classes to logically group classes at one place so that it can be more readable and maintainable. It can also access private data members of the class.


Syntax :
Class Outer_class{
                Class Nested_class{
                // Body of nested class
}
}


What are the advantages of using nested classes :
  •  Imagine the case in which a certain class is being used only once from within another class, then there is no obvious need to add a clutter to the enclosing package by defining a top-level-class that will merely be used by only one another class.

  • Another very important advantage of having nested classes is the fact that nested classes will be able to access all the class members of their enclosing top-level-class (including the private member methods and variables).

  • Another advantage of this feature can be seen when developing event-based applications where action and event listeners can be defined as nested classes rather than having them as separate individual top-level-classes.    


  •       Code optimization as we need less code to write.



Types of Nested classes:


                              


Non- Static nested class : 

Non static nested classes are defined within the top-level-classes and they are bound by the scope of their enclosing class, non-static nested classes can have direct access into all of the members (even the private ones) of their enclosing class, on the other hand, the enclosing class doesn’t have any access to the members of the enclosed nested class.
·        

      Member Class : 

      A class that is declared inside a class but outside the method of the class. There are possible two ways through which we can access inner class are – from within a class and from outside the class.  


Example : (from within the class)


class OuterClass{
    private int x = 20;
   
    public class InnerClass{
        public void show(){
        System.out.println("x = "+x);
        }
    }
    public void display(){
        InnerClass inner = new InnerClass();
        inner.show();
    }   
    public static void main(String[] args){  
    OuterClass o = new OuterClass();
    o.display();
    }  
}



Example : (from outside the class)

class OuterClass{
    private int x = 20;
   
    public class InnerClass{
        public void show(){
        System.out.println("x = "+x);       }  
          }  
 }
class Test{  
    public static void main(String[] args){
    OuterClass o = new OuterClass();
        OuterClass.InnerClass inner = o.new InnerClass();
        inner.show();
    }  
}



·         Anonymous class :
      
      Java supports the definition of un-named inner classes, these classes differ from the inner classes in only one thing, which is that they are un-named, hence came the name “anonymous”. Anonymous classes can have direct access to all of the class members of the top-level-class in which they are defined.

Example : (using abstract class)

abstract class Person{
    abstract void show();
}
class NewClass{  
    public static void main(String[] args){
        Person p = new Person() {

            @Override
            public void show() {
                System.out.println("I am in Show method");
            }
        };       
        p.show();
    }  
}



Example : (using interface)

interface Person{
    void show();
}
class NewClass{  
    public static void main(String[] args){
        Person p = new Person() {

            @Override
            public void show() {
                System.out.println("I am in Show method");
            }
        };       
        p.show();
    }  
}



      Local Class :
   
       Local inner class is a class which is created inside a method body. If you want to access the local class you always need to instantiate inside the method only. It can only access final member of the class .


Example:

public class Test{
    private int var_data = 30;
    void display(){
        class Local_Class{
            public void msg(){
                System.out.println(var_data);
            }
        }
        Local_Class local = new Local_Class();
        local.msg();
    }
 
    public static void  main(String[] args){
        Test t = new Test();
        t.display();
    }

}


Output: 
30


Static Nested Class:

A static class that is created inside a class is called Static Nested class.A static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference. It can access static data members of outer class including private.

Example:

public class Test{
    private static int var_data = 30;
 
        static class Static_Inner_Class{
            public void msg(){
                System.out.println("private static data "+var_data);
            }
        }
     
    public static void  main(String[] args){
        Test.Static_Inner_Class t = new Test.Static_Inner_Class();
        t.msg();
    }
}

Output:

private static data 30


Example (Using static method): 

public class Test{
    private static int var_data = 30;
 
        static class Static_Inner_Class{
             static void msg(){
                System.out.println("private static data "+var_data);
            }
        }
     
    public static void  main(String[] args){
        Test.Static_Inner_Class.msg();
    }

}

Output:

private static data 30