Java – Delete Files

Java – Delete Files ”; Previous Next Deleting Files in Java To delete a file in Java, you can use the File.delete() method. This method deletes the files or directory from the given path. Syntax Following is the syntax of deleting a file using File.delete() method − File file = new File(“C:/java/hello.txt”); if(file.exists()){ file.delete(); } Deleting File from Current Directory Following is the example to demonstrate File.delete() method usage to delete an existing file in current directory− Example package com.tutorialspoint; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class FileTest { public static void main(String args[]) throws IOException { BufferedWriter out = new BufferedWriter (new FileWriter(“test.txt”)); out.write(“test data”); out.close(); File file = new File(“test.txt”); if(file.exists()) { boolean success = file.delete(); if (success) { System.out.println(“The file has been successfully deleted.”); }else { System.out.println(“The file deletion failed.”); } }else { System.out.println(“The file is not present.”); } } } Output The above code would create file test.txt and would write given numbers in binary format. Same would be the output on the stdout screen. This will produce the following result − The file has been successfully deleted. Deleting File That Does Not Exist Following is the example to demonstrate File.delete() method call to delete an non-existing file in current directory. As file is not present, it returns false as result. Example package com.tutorialspoint; import java.io.File; import java.io.IOException; public class FileTest { public static void main(String args[]) throws IOException { File file = new File(“test1.txt”); boolean success = file.delete(); if (success) { System.out.println(“The file has been successfully deleted.”); }else { System.out.println(“The file deletion failed.”); } } } Output The above code would create file test.txt and would write given numbers in binary format. Same would be the output on the stdout screen. This will produce the following result − The file deletion failed. Deleting All Files From Given Directory Following is the example to demonstrate File.delete() method usage to delete all files in given directory recursively. Example package com.tutorialspoint; import java.io.File; import java.io.IOException; public class FileTest { public static void deleteFiles(File dirPath) { File filesList[] = dirPath.listFiles(); for(File file : filesList) { if(file.isFile()) { file.delete(); } else { deleteFiles(file); } } } public static void main(String args[]) throws IOException { //Creating a File object for directory File file = new File(“D:\test”); //List of all files and directories deleteFiles(file); System.out.println(“Files deleted.”); } } Output The above code would create file test.txt and would write given numbers in binary format. Same would be the output on the stdout screen. This will produce the following result − Files deleted. Print Page Previous Next Advertisements ”;

Java – Shutdown Hook

Java – JVM Shutdown Hook ”; Previous Next JVM Shutdown The following are the two different ways for JVM shutdown – A controlled process: JVM starts to shut down its process if the System.exit() method is called, CTRL+C is pressed, or if the last non-daemon thread terminates. An abrupt manner: JVM starts to shut down its process if it receives a kill signal, the Runtime.getRuntime().halt() method is called, or any kind of OS panic. JVM Shutdown Hook A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt. Note that daemon threads will continue to run during the shutdown sequence, as will non-daemon threads if shutdown was initiated by invoking the exit method. JVM Shutdown Hook: The addShutdownHook(Thread hook) Method The Runtime addShutdownHook(Thread hook) method registers a new virtual-machine shutdown hook. Declaration Following is the declaration for java.lang.Runtime.addShutdownHook() method public void addShutdownHook(Thread hook) Parameters hook − An initialized but unstarted Thread object. Return Value This method does not return a value. Exception IllegalArgumentException − If the specified hook has already been registered, or if it can be determined that the hook is already running or has already been run. IllegalStateException − If the virtual machine is already in the process of shutting down. SecurityException − If a security manager is present and it denies RuntimePermission(“shutdownHooks”). Example of JVM Shutdown Hook In this example, we”re creating a class CustomThread by extending Thread class. This thread object will be used as JVM Shutdown hook. CustomThread class has run() method implementation. In main class TestThread, we”ve added a shutdown hook using Runtime.getRuntime().addShutdownHook() method, by passing it a thread object. In output you can verify that CustomThread run() method is called when program is about to exit. package com.tutorialspoint; class CustomThread extends Thread { public void run() { System.out.println(“JVM is shutting down.”); } } public class TestThread { public static void main(String args[]) throws InterruptedException { try { // register CustomThread as shutdown hook Runtime.getRuntime().addShutdownHook(new CustomThread()); // print the state of the program System.out.println(“Program is starting…”); // cause thread to sleep for 3 seconds System.out.println(“Waiting for 3 seconds…”); Thread.sleep(3000); // print that the program is closing System.out.println(“Program is closing…”); } catch (Exception e) { e.printStackTrace(); } } } Output Program is starting… Waiting for 3 seconds… Program is closing… JVM is shutting down. More Example of JVM Shutdown Hook Example 1 In this example, we”re creating a class CustomThread by implementing Runnable interface. This thread object will be used as JVM Shutdown hook. CustomThread class has run() method implementation. In main class TestThread, we”ve added a shutdown hook using Runtime.getRuntime().addShutdownHook() method, by passing it a thread object. In output you can verify that CustomThread run() method is called when program is about to exit. package com.tutorialspoint; class CustomThread implements Runnable { public void run() { System.out.println(“JVM is shutting down.”); } } public class TestThread { public static void main(String args[]) throws InterruptedException { try { // register CustomThread as shutdown hook Runtime.getRuntime().addShutdownHook(new Thread(new CustomThread())); // print the state of the program System.out.println(“Program is starting…”); // cause thread to sleep for 3 seconds System.out.println(“Waiting for 3 seconds…”); Thread.sleep(3000); // print that the program is closing System.out.println(“Program is closing…”); } catch (Exception e) { e.printStackTrace(); } } } Output Program is starting… Waiting for 3 seconds… Program is closing… JVM is shutting down. Example 2 We can remove the shutdown hook as well using removeShutdownHook(). In this example, we”re creating a class CustomThread by implementing Runnable interface. This thread object will be used as JVM Shutdown hook. CustomThread class has run() method implementation. In main class TestThread, we”ve added a shutdown hook using Runtime.getRuntime().addShutdownHook() method, by passing it a thread object. As last statement, we”re removing the hook using Runtime.getRuntime().removeShutdownHook() method package com.tutorialspoint; class CustomThread implements Runnable { public void run() { System.out.println(“JVM is shutting down.”); } } public class TestThread { public static void main(String args[]) throws InterruptedException { try { Thread hook = new Thread(new CustomThread()); // register Message as shutdown hook Runtime.getRuntime().addShutdownHook(hook); // print the state of the program System.out.println(“Program is starting…”); // cause thread to sleep for 3 seconds System.out.println(“Waiting for 3 seconds…”); Thread.sleep(3000); // print that the program is closing System.out.println(“Program is closing…”); Runtime.getRuntime().removeShutdownHook(hook); } catch (Exception e) { e.printStackTrace(); } } } Output Program is starting… Waiting for 3 seconds… Program is closing… Print Page Previous Next Advertisements ”;

Java – I/O Streams

Java – Files and I/O ”; Previous Next The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, object, localized characters, etc. Stream A stream can be defined as a sequence of data. There are two kinds of Streams − InPutStream − The InputStream is used to read data from a source. OutPutStream − The OutputStream is used for writing data to a destination. Java provides strong but flexible support for I/O related to files and networks but this tutorial covers very basic functionality related to streams and I/O. We will see the most commonly used examples one by one − Byte Streams Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to byte streams but the most frequently used classes are, FileInputStream and FileOutputStream. Following is an example which makes use of these two classes to copy an input file into an output file − Example import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class CopyFile { public static void main(String args[]) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream(“input.txt”); out = new FileOutputStream(“output.txt”); int c; while ((c = in.read()) != -1) { out.write(c); } }finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } } Now let”s have a file input.txt with the following content − This is test for copy file. As a next step, compile the above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let”s put the above code in CopyFile.java file and do the following − $javac CopyFile.java $java CopyFile Character Streams Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character streams are used to perform input and output for 16-bit unicode. Though there are many classes related to character streams but the most frequently used classes are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time. We can re-write the above example, which makes the use of these two classes to copy an input file (having unicode characters) into an output file − Example import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class CopyFile { public static void main(String args[]) throws IOException { FileReader in = null; FileWriter out = null; try { in = new FileReader(“input.txt”); out = new FileWriter(“output.txt”); int c; while ((c = in.read()) != -1) { out.write(c); } }finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } } Now let”s have a file input.txt with the following content − This is test for copy file. As a next step, compile the above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let”s put the above code in CopyFile.java file and do the following − $javac CopyFile.java $java CopyFile Standard Streams All the programming languages provide support for standard I/O where the user”s program can take input from a keyboard and then produce an output on the computer screen. If you are aware of C or C++ programming languages, then you must be aware of three standard devices STDIN, STDOUT and STDERR. Similarly, Java provides the following three standard streams − Standard Input − This is used to feed the data to user”s program and usually a keyboard is used as standard input stream and represented as System.in. Standard Output − This is used to output the data produced by the user”s program and usually a computer screen is used for standard output stream and represented as System.out. Standard Error − This is used to output the error data produced by the user”s program and usually a computer screen is used for standard error stream and represented as System.err. Following is a simple program, which creates InputStreamReader to read standard input stream until the user types a “q” − Example import java.io.InputStreamReader; public class ReadConsole { public static void main(String args[]) throws IOException { InputStreamReader cin = null; try { cin = new InputStreamReader(System.in); System.out.println(“Enter characters, ”q” to quit.”); char c; do { c = (char) cin.read(); System.out.print(c); } while(c != ”q”); }finally { if (cin != null) { cin.close(); } } } } Let”s keep the above code in ReadConsole.java file and try to compile and execute it as shown in the following program. This program continues to read and output the same character until we press ”q” − $javac ReadConsole.java $java ReadConsole Enter characters, ”q” to quit. 1 1 e e q q Reading and Writing Files As described earlier, a stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination. Here is a hierarchy of classes to deal with Input and Output streams. The two important streams are FileInputStream and FileOutputStream, which would be discussed in this tutorial. FileInputStream This stream is used for reading data from the files. Objects can be created using the keyword new and there are several types of constructors available. Following constructor takes a file name as a string to create an input stream object to read the file − InputStream f = new FileInputStream(“C:/java/hello”); Following constructor takes a file object to create an input stream object to read the file. First we create a file object using File() method as follows − File f = new File(“C:/java/hello”); InputStream f = new FileInputStream(f); Once you have InputStream object in hand, then there is a list

Java – Anonymous Class

Java – Anonymous Classes ”; Previous Next Java Anonymous Class An anonymous class in Java is an inner class which is declared without any class name at all. In other words, a nameless inner class in Java is called an anonymous inner class. Since it does not have a name, it cannot have a constructor because we know that a constructor name is the same as the class name. Use of Java Anonymous Inner Classes Anonymous inner classes are used when you want to create a simple class that is needed for one time only for a specific purpose. For example, implementing an interface or extending a class. Defining Anonymous Class in Java You can define an anonymous inner class and create its object using the new operator at the same time in one step. Syntax The syntax of anonymous nested class is as follows − new(argument-list){ // Anonymous class body } Types of Anonymous Inner Classes in Java Anonymous inner class that extends a class Anonymous inner class that implements an interface Anonymous inner class as an argument 1. Anonymous inner class that extends a class You can use an anonymous inner class to extend a class in Java. Example: Anonymous inner class that extends a class In the following example,we”re using a new keyword to create an object of the anonymous inner class that has a reference of parent class type. package com.tutorialspoint; class Car { public void engineType() { System.out.println(“Turbo Engine”); } } public class Tester { public static void main(String args[]) { Car c1 = new Car(); c1.engineType(); Car c2 = new Car() { @Override public void engineType() { System.out.println(“V2 Engine”); } }; c2.engineType(); } } Output If you compile and execute the above program, you will get the following result − Turbo Engine V2 Engine 2. Anonymous inner class that implements an interface You can use an anonymous inner class to implement an interface in Java. Example: Anonymous inner class that implements an interface In the following example,we”re using a new keyword to create an object of the anonymous inner class that has a reference of an interface type. package com.tutorialspoint; interface Software { public void develop(); } public class Tester { public static void main(String args[]) { Software s = new Software() { @Override public void develop() { System.out.println(“Software Developed in Java”); } }; s.develop(); System.out.println(s.getClass().getName()); } } Output If you compile and execute the above program, you will get the following result − Software Developed in Java com.tutorialspoint.Tester$1 3. Anonymous inner class as an argument We can use the anonymous inner class as an argument so that it can be passed to methods or constructors. Example: Anonymous inner class as an argument In the following example,we”re passing an anonymous inner class as an argument to one method. package com.tutorialspoint; abstract class Engine { public abstract void engineType(); } class Vehicle { public void transport(Engine e) { e.engineType(); } } public class Tester { public static void main(String args[]) { Vehicle v = new Vehicle(); v.transport(new Engine() { @Override public void engineType() { System.out.println(“Turbo Engine”); } }); } } Output If you compile and execute the above program, you will get the following result − Turbo Engine Print Page Previous Next Advertisements ”;

Java – Joining Threads

Java – Joining Threads ”; Previous Next Once a Thread object is created, you can start it by calling start() method, which executes a call to run() method. With multiple threads running, we can block current thread until another thread terminates. Joining Threads in Java Joining threads in Java refers for waiting (or, blocking) a thread until another thread finishes its execution. The join() method of the Thread class is used for this purpose. Syntax Following is a simple syntax of join() method − void join(); Overloaded Thread.join() Methods The following are the three overloaded join() method – join() − The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates. join(long millisec) − The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes. join(long millisec, int nanos) − The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds + nanoseconds passes. Example of Joining Threads in Java In this example, we”re creating a class RunnableDemo by implementing Runnable interface. RunnableDemo class has run() method implementation. In main class TestThread, we”ve created the RunnableDemo objects and using those objects we”ve created two Thread objects. When Thread.start() method is called on each thread objects, threads start processing and program is executed. Using join() method, we”re blocking the current thread which ensure that once thread is complete then only next thread will start. package com.tutorialspoint; class RunnableDemo implements Runnable { RunnableDemo( ) { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: New”); } public void run() { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Running”); for(int i = 4; i > 0; i–) { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + i); } System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Dead”); } } public class TestThread { public static void main(String args[]) throws InterruptedException { Thread t1 = new Thread( new RunnableDemo(), “Thread-1”); Thread t2 = new Thread( new RunnableDemo(), “Thread-2”); Thread t3 = new Thread( new RunnableDemo(), “Thread-3″); // start t1 thread and join main thread t1.start(); t1.join(); // t2 will start when t1 is dead t2.start(); t2.join(); // t3 will start when t2 is dead t3.start(); } } Output Thread: Thread-1, State: New Thread: Thread-2, State: New Thread: Thread-1, State: Running Thread: Thread-1, 4 Thread: Thread-1, 3 Thread: Thread-1, 2 Thread: Thread-1, 1 Thread: Thread-1, State: Dead Thread: Thread-2, State: Running Thread: Thread-2, 4 Thread: Thread-2, 3 Thread: Thread-2, 2 Thread: Thread-2, 1 Thread: Thread-2, State: Dead More Example of Joining Threads in Java Example 1 In this example, we”re creating a class RunnableDemo by implementing Runnable interface. RunnableDemo class has run() method implementation. In main class TestThread, we”ve created the RunnableDemo objects and using those objects we”ve created two Thread objects. When Thread.start() method is called on each thread objects, threads start processing and program is executed. Using join(long millisec) method, we”re blocking the current thread for 200 millisecs which ensure that once thread is complete or a delay of 200 ms occurred then only next thread will start. package com.tutorialspoint; class RunnableDemo implements Runnable { RunnableDemo( ) { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: New”); } public void run() { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Running”); for(int i = 4; i > 0; i–) { try { Thread.sleep(50); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + i); } System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Dead”); } } public class TestThread { public static void main(String args[]) throws InterruptedException { Thread t1 = new Thread( new RunnableDemo(), “Thread-1”); Thread t2 = new Thread( new RunnableDemo(), “Thread-2”); Thread t3 = new Thread( new RunnableDemo(), “Thread-3″); // start t1 thread and join main thread t1.start(); t1.join(200); // t2 will start when t1 is dead or 200 ms is elapsed t2.start(); t2.join(200); // t3 will start when t2 is dead or 200 ms is elapsed t3.start(); } } Output Thread: main, State: New Thread: main, State: New Thread: main, State: New Thread: Thread-1, State: Running Thread: Thread-1, 4 Thread: Thread-1, 3 Thread: Thread-1, 2 Thread: Thread-2, State: Running Thread: Thread-1, 1 Thread: Thread-1, State: Dead Thread: Thread-2, 4 Thread: Thread-2, 3 Thread: Thread-2, 2 Thread: Thread-3, State: Running Thread: Thread-2, 1 Thread: Thread-2, State: Dead Thread: Thread-3, 4 Thread: Thread-3, 3 Thread: Thread-3, 2 Thread: Thread-3, 1 Thread: Thread-3, State: Dead Example 2 In this example, we”re creating a class RunnableDemo by implementing Runnable interface. RunnableDemo class has run() method implementation. In main class TestThread, we”ve created the RunnableDemo objects and using those objects we”ve created two Thread objects. When Thread.start() method is called on each thread objects, threads start processing and program is executed. Using join(long millisec, long nanoseconds) method, we”re blocking the current thread for 200 millisecs and 100000 nanosecs which ensure that once thread is complete or a delay of 201 ms occurred then only next thread will start. package com.tutorialspoint; class RunnableDemo implements Runnable { RunnableDemo( ) { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: New”); } public void run() { System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Running”); for(int i = 4; i > 0; i–) { try { Thread.sleep(49); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + i); } System.out.println(“Thread: ” + Thread.currentThread().getName() + “, ” + “State: Dead”); } } public class TestThread { public static void main(String args[]) throws InterruptedException { Thread t1 = new Thread( new RunnableDemo(), “Thread-1”); Thread t2 = new Thread( new RunnableDemo(), “Thread-2”); Thread t3 = new Thread( new RunnableDemo(), “Thread-3”); // start t1 thread and join main thread t1.start(); t1.join(200,100000); // t2 will start when t1

Java – Files

Java – File Class ”; Previous Next Java File Class Java File class represents the files and directory pathnames in an abstract manner. This class is used for creation of files and directories, file searching, file deletion, etc. The File object represents the actual file/directory on the disk. File Class Constructors Following is the list of constructors to create a File object. Sr.No. Method & Description 1 File(File parent, String child) This constructor creates a new File instance from a parent abstract pathname and a child pathname string. 2 File(String pathname) This constructor creates a new File instance by converting the given pathname string into an abstract pathname. 3 File(String parent, String child) This constructor creates a new File instance from a parent pathname string and a child pathname string. 4 File(URI uri) This constructor creates a new File instance by converting the given file: URI into an abstract pathname. File Class Methods Once you have File object in hand, then there is a list of helper methods which can be used to manipulate the files. Sr.No. Method & Description 1 public String getName() Returns the name of the file or directory denoted by this abstract pathname. 2 public String getParent() Returns the pathname string of this abstract pathname”s parent, or null if this pathname does not name a parent directory. 3 public File getParentFile() Returns the abstract pathname of this abstract pathname”s parent, or null if this pathname does not name a parent directory. 4 public String getPath() Converts this abstract pathname into a pathname string. 5 public boolean isAbsolute() Tests whether this abstract pathname is absolute. Returns true if this abstract pathname is absolute, false otherwise. 6 public String getAbsolutePath() Returns the absolute pathname string of this abstract pathname. 7 public boolean canRead() Tests whether the application can read the file denoted by this abstract pathname. Returns true if and only if the file specified by this abstract pathname exists and can be read by the application; false otherwise. 8 public boolean canWrite() Tests whether the application can modify to the file denoted by this abstract pathname. Returns true if and only if the file system actually contains a file denoted by this abstract pathname and the application is allowed to write to the file; false otherwise. 9 public boolean exists() Tests whether the file or directory denoted by this abstract pathname exists. Returns true if and only if the file or directory denoted by this abstract pathname exists; false otherwise. 10 public boolean isDirectory() Tests whether the file denoted by this abstract pathname is a directory. Returns true if and only if the file denoted by this abstract pathname exists and is a directory; false otherwise. 11 public boolean isFile() Tests whether the file denoted by this abstract pathname is a normal file. A file is normal if it is not a directory and, in addition, satisfies other system-dependent criteria. Any non-directory file created by a Java application is guaranteed to be a normal file. Returns true if and only if the file denoted by this abstract pathname exists and is a normal file; false otherwise. 12 public long lastModified() Returns the time that the file denoted by this abstract pathname was last modified. Returns a long value representing the time the file was last modified, measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970), or 0L if the file does not exist or if an I/O error occurs. 13 public long length() Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this pathname denotes a directory. 14 public boolean createNewFile() throws IOException Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. Returns true if the named file does not exist and was successfully created; false if the named file already exists. 15 public boolean delete() Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted. Returns true if and only if the file or directory is successfully deleted; false otherwise. 16 public void deleteOnExit() Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates. 17 public String[] list() Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname. 18 public String[] list(FilenameFilter filter) Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter. 20 public File[] listFiles() Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname. 21 public File[] listFiles(FileFilter filter) Returns an array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter. 22 public boolean mkdir() Creates the directory named by this abstract pathname. Returns true if and only if the directory was created; false otherwise. 23 public boolean mkdirs() Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Returns true if and only if the directory was created, along with all necessary parent directories; false otherwise. 24 public boolean renameTo(File dest) Renames the file denoted by this abstract pathname. Returns true if and only if the renaming succeeded; false otherwise. 25 public boolean setLastModified(long time) Sets the last-modified time of the file or directory named by this abstract pathname. Returns true if and only if the operation succeeded; false otherwise. 26 public boolean setReadOnly() Marks the file or directory named by this abstract pathname so that only read operations are allowed. Returns true if and only if the operation succeeded; false otherwise. 27 public static File createTempFile(String prefix, String suffix, File directory) throws IOException Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its

Java – Interfaces

Java – Interfaces ”; Previous Next Java Interfaces Java interface is a collection of abstract methods. The interface is used to achieve abstraction in which you can define methods without their implementations (without having the body of the methods). An interface is a reference type and is similar to the class. Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods. Writing an interface is similar to writing a class. However, a class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements. Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class. Java Interfaces and Classes: Similarities and Differences Similarities An interface is similar to a class in the following ways − An interface can contain any number of methods. An interface is written in a file with a .java extension, with the name of the interface matching the name of the file. The byte code of an interface appears in a .class file. Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name. Differences However, an interface is different from a class in several ways, including − You cannot instantiate an interface. An interface does not contain any constructors. All of the methods in an interface are abstract. An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final. An interface is not extended by a class; it is implemented by a class. An interface can extend multiple interfaces. Declaring an Interface in Java The interface keyword is used to declare an interface. Here is a simple example to declare an interface − Example to Declare a Java Interface Following is an example of an interface − /* File name : NameOfInterface.java */ import java.lang.*; // Any number of import statements public interface NameOfInterface { // Any number of final, static fields // Any number of abstract method declarations } Propeties of Java Interface Interfaces have the following properties − An interface is implicitly abstract. You do not need to use the abstract keyword while declaring an interface. Each method in an interface is also implicitly abstract, so the abstract keyword is not needed. Methods in an interface are implicitly public. Example /* File name : Animal.java */ interface Animal { public void eat(); public void travel(); } Implementing Interfaces in Java When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract. A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration. Example: Implement an Interface in Java /* File name : MammalInt.java */ public class MammalInt implements Animal { public void eat() { System.out.println(“Mammal eats”); } public void travel() { System.out.println(“Mammal travels”); } public int noOfLegs() { return 0; } public static void main(String args[]) { MammalInt m = new MammalInt(); m.eat(); m.travel(); } } interface Animal { public void eat(); public void travel(); } Output Mammal eats Mammal travels Rules for defining overriding methods in Java Interfaces When overriding methods defined in interfaces, there are several rules to be followed − Checked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method. The signature of the interface method and the same return type or subtype should be maintained when overriding the methods. An implementation class itself can be abstract and if so, interface methods need not be implemented. Rules for implementing Java Interfaces When implementation interfaces, there are several rules − A class can implement more than one interface at a time. A class can extend only one class, but implement many interfaces. An interface can extend another interface, in a similar way as a class can extend another class. Extending Java Interfaces An interface can extend another interface in the same way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface. Example: How to Extend Java Interface The following Sports interface is extended by Hockey and Football interfaces. // Filename: Sports.java public interface Sports { public void setHomeTeam(String name); public void setVisitingTeam(String name); } // Filename: Football.java public interface Football extends Sports { public void homeTeamScored(int points); public void visitingTeamScored(int points); public void endOfQuarter(int quarter); } // Filename: Hockey.java public interface Hockey extends Sports { public void homeGoalScored(); public void visitingGoalScored(); public void endOfPeriod(int period); public void overtimePeriod(int ot); } The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements Hockey needs to implement all six methods. Similarly, a class that implements Football needs to define the three methods from Football and the two methods from Sports. Example interface Sports { public void setHomeTeam(String name); public void setVisitingTeam(String name); } interface Football extends Sports { public void homeTeamScored(int points); public void visitingTeamScored(int points); public void endOfQuarter(int quarter); } interface Hockey extends Sports { public void homeGoalScored(); public void visitingGoalScored(); public void endOfPeriod(int period); public void overtimePeriod(int ot); } public class HockeyDemo implements Hockey { public void setHomeTeam(String name) { System.out.println(“Home team: ” + name); } public void setVisitingTeam(String name) {} public void homeGoalScored() {} public void visitingGoalScored() {} public void endOfPeriod(int period) {} public void overtimePeriod(int ot) {} public static void main(String[] args) { Hockey hockeyDemo = new HockeyDemo(); hockeyDemo.setHomeTeam(“India”); } } Output Home team: India Extending Multiple Java Interfaces A Java class can only extend one parent class. Multiple inheritance is not allowed.

Java – URL Processing

Java – URL Processing ”; Previous Next URL stands for Uniform Resource Locator and represents a resource on the World Wide Web, such as a Web page or FTP directory. This section shows you how to write Java programs that communicate with a URL. A URL can be broken down into parts, as follows − protocol://host:port/path?query#ref Examples of protocols include HTTP, HTTPS, FTP, and File. The path is also referred to as the filename, and the host is also called the authority. The following is a URL to a web page whose protocol is HTTP − https://www.amrood.com/index.htm?language=en#j2se Notice that this URL does not specify a port, in which case the default port for the protocol is used. With HTTP, the default port is 80. Constructors The java.net.URL class represents a URL and has a complete set of methods to manipulate URL in Java. The URL class has several constructors for creating URLs, including the following − Sr.No. Constructors & Description 1 public URL(String protocol, String host, int port, String file) throws MalformedURLException Creates a URL by putting together the given parts. 2 public URL(String protocol, String host, String file) throws MalformedURLException Identical to the previous constructor, except that the default port for the given protocol is used. 3 public URL(String url) throws MalformedURLException Creates a URL from the given String. 4 public URL(URL context, String url) throws MalformedURLException Creates a URL by parsing together the URL and String arguments. The URL class contains many methods for accessing the various parts of the URL being represented. Some of the methods in the URL class include the following − Sr.No. Method & Description 1 public equals(Object obj) This method compares this URL for equality with another object. 2 public String getAuthority() This method returns the authority of the URL. 3 public Object getContent() This method returns the contents of this URL. 4 public Object getContent(Class<?>[] classes) This method returns the contents of this URL. 5 public int getDefaultPort() This method returns the default port for the protocol of the URL. 6 public String getFile() This method returns the filename of the URL. 7 public String getHost() This method returns the host of the URL. 8 public String getPath() This method returns the path of the URL. 9 public int getPort() This method returns the port of the URL. 10 public String getProtocol() This method returns the protocol of the URL. 11 public String getQuery() This method returns the query part of the URL. 12 public String getRef() This method returns the reference part of the URL. 13 public String getUserInfo() This method returns the userInfo part of the URL. 14 public int hashCode() This method creates and return an integer suitable for hash table indexing. 15 public URLConnection openConnection() This method returns a URLConnection instance that represents a connection to the remote object referred to by the URL. 16 public URLConnection openConnection(Proxy proxy) This method acts as openConnection(), except that the connection will be made through the specified proxy; Protocol handlers that do not support proxing will ignore the proxy parameter and make a normal connection. 17 public InputStream openStream() This method opens a connection to this URL and returns an InputStream for reading from that connection. 18 public boolean sameFile(URL other) This method compares two URLs, excluding the fragment component. 19 public static void setURLStreamHandlerFactory(URLStreamHandlerFactory fac) This method sets an application”s URLStreamHandlerFactory. 20 public String toExternalForm() This method constructs and return a string representation of this URL. 21 public String toString() This method constructs and return a string representation of this URL. 22 public String toURI() This method returns a URI equivalent to this URL. Example The following URLDemo program demonstrates the various parts of a URL. A URL is entered on the command line, and the URLDemo program outputs each part of the given URL. // File Name : URLDemo.java import java.io.IOException; import java.net.URL; public class URLDemo { public static void main(String [] args) { try { URL url = new URL(“https://www.tutorialspoint.com/index.htm?language=en#j2se”); System.out.println(“URL is ” + url.toString()); System.out.println(“protocol is ” + url.getProtocol()); System.out.println(“authority is ” + url.getAuthority()); System.out.println(“file name is ” + url.getFile()); System.out.println(“host is ” + url.getHost()); System.out.println(“path is ” + url.getPath()); System.out.println(“port is ” + url.getPort()); System.out.println(“default port is ” + url.getDefaultPort()); System.out.println(“query is ” + url.getQuery()); System.out.println(“ref is ” + url.getRef()); } catch (IOException e) { e.printStackTrace(); } } } A sample run of the this program will produce the following result − Output URL is https://www.tutorialspoint.com/index.htm?language=en#j2se protocol is https authority is www.tutorialspoint.com file name is /index.htm?language=en host is www.tutorialspoint.com path is /index.htm port is -1 default port is 443 query is language=en ref is j2se URLConnections Class Methods The openConnection() method returns a java.net.URLConnection, an abstract class whose subclasses represent the various types of URL connections. For example − If you connect to a URL whose protocol is HTTP, the openConnection() method returns an HttpURLConnection object. If you connect to a URL that represents a JAR file, the openConnection() method returns a JarURLConnection object, etc. The URLConnection class has many methods for setting or determining information about the connection, including the following − Sr.No. Method & Description 1 void addRequestProperty(String key, String value) Adds a general request property specified by a key-value pair. 2 boolean getAllowUserInteraction() Returns the value of the allowUserInteraction field for this object. 3 int getConnectTimeout() Returns setting for connect timeout. 4 Object getContent() Retrieves the contents of this URL connection. 5 Object getContent(Class[] classes) Retrieves the contents of this URL connection. 6 String getContentEncoding() Returns the value of the content-encoding header field. 7 int getContentLength() Returns the value of the content-length header field. 8 long getContentLengthLong() Returns the value of the content-length header field as long. 9 String getContentType() Returns the value of the content-type header field. 10 long getDate() Returns the value of the date header field. 11 static boolean getDefaultAllowUserInteraction() Returns the default value of the allowUserInteraction field. 12 boolean getDefaultUseCaches() Returns the default value of a URLConnection”s useCaches flag. 13 static boolean getDefaultUseCaches(String protocol) Returns

Java – Thread Scheduler

Java – Scheduling Threads with Examples ”; Previous Next Java is a multi-threaded programming language which means we can develop multi-threaded program using Java. A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs. By definition, multitasking is when multiple processes share common processing resources such as a CPU. Multi-threading extends the idea of multitasking into applications where you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application. Multi-threading enables you to write in a way where multiple activities can proceed concurrently in the same program. Java provides a java.util.concurrent.ScheduledExecutorService interface which is a subinterface of ExecutorService interface, and supports future and/or periodic execution of tasks/threads. Following are few important and useful methods this interface. ScheduledExecutorService Methods Sr.No. Method & Description 1 <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) Creates and executes a ScheduledFuture that becomes enabled after the given delay. 2 ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) Creates and executes a one-shot action that becomes enabled after the given delay. 3 ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is executions will commence after initialDelay then initialDelay+period, then initialDelay + 2 * period, and so on. 4 ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next. Example 1 The following TestThread program shows usage of ScheduledExecutorService interface in thread based environment to schedule a task to run after 2 seconds at interval of 2 seconds in time period of 10 seconds showcasing usage of scheduleAtFixedRate() and schedule() methods. package com.tutorialspoint; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; public class TestThread { public static void main(final String[] arguments) throws InterruptedException { final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); final ScheduledFuture<?> beepHandler = scheduler.scheduleAtFixedRate(new BeepTask(), 2, 2, TimeUnit.SECONDS); scheduler.schedule(new Runnable() { @Override public void run() { beepHandler.cancel(true); scheduler.shutdown(); } }, 10, TimeUnit.SECONDS); } static class BeepTask implements Runnable { public void run() { System.out.println(“beep”); } } } Output beep beep beep beep beep Example 2 The following TestThread program shows usage of ScheduledExecutorService interface in thread based environment to schedule a task to run after 2 seconds at interval of 2 seconds in time period of 10 seconds showcasing usage of scheduleAtFixedDelay() and schedule() methods. package com.tutorialspoint; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; public class TestThread { public static void main(final String[] arguments) throws InterruptedException { final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); final ScheduledFuture<?> beepHandler = scheduler.scheduleAtFixedDelay(new BeepTask(), 2, 2, TimeUnit.SECONDS); scheduler.schedule(new Runnable() { @Override public void run() { beepHandler.cancel(true); scheduler.shutdown(); } }, 10, TimeUnit.SECONDS); } static class BeepTask implements Runnable { public void run() { System.out.println(“beep”); } } } Output beep beep beep beep Example 3 The following TestThread program shows usage of ScheduledExecutorService interface in thread based environment to schedule a task to run once after 2 seconds in time period of 10 seconds showcasing usage of schedule() method. package com.tutorialspoint; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; public class TestThread { public static void main(final String[] arguments) throws InterruptedException { final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); final ScheduledFuture<?> beepHandler = scheduler.schedule(new BeepTask(), 2, TimeUnit.SECONDS); scheduler.schedule(new Runnable() { @Override public void run() { beepHandler.cancel(true); scheduler.shutdown(); } }, 10, TimeUnit.SECONDS); } static class BeepTask implements Runnable { public void run() { System.out.println(“beep”); } } } Output beep Print Page Previous Next Advertisements ”;

Java – Finally Block

Java – Finally Block ”; Previous Next The finally Block in Java The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. Syntax: Finally Block A finally block appears at the end of the catch blocks and has the following syntax − try { // Protected code } catch (ExceptionType1 e1) { // Catch block } catch (ExceptionType2 e2) { // Catch block } catch (ExceptionType3 e3) { // Catch block }finally { // The finally block always executes. } Points To Remember While Using Finally Block A catch clause cannot exist without a try statement. It is not compulsory to have finally clauses whenever a try/catch block is present. The try block cannot be present without either catch clause or finally clause. Any code cannot be present in between the try, catch, finally blocks. finally block is not executed in case exit() method is called before finally block or a fatal error occurs in program execution. finally block is executed even method returns a value before finally block. Why Java Finally Block Used? Java finally block can be used for clean-up (closing) the connections, files opened, streams, etc. those must be closed before exiting the program. It can also be used to print some final information. Java Finally Block Example Here is code segment showing how to use finally after try/catch statements after handling exception. In this example, we”re creating an error accessing an element of an array using invalid index. The catch block is handling the exception and printing the same. Now in finally block, we”re printing a statement signifying that finally block is getting executed. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { int a[] = new int[2]; try { System.out.println(“Access element three :” + a[3]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(“Exception thrown :” + e); }finally { a[0] = 6; System.out.println(“First element value: ” + a[0]); System.out.println(“The finally statement is executed”); } } } Output Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed More Examples Example 1 Here is code segment showing how to use finally after try/catch statements even exception is not handled. In this example, we”re creating an error accessing an element of an array using invalid index. As the catch block is not handling the exception, we can check in output that finally block is printing a statement signifying that finally block is getting executed. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { int a[] = new int[2]; try { System.out.println(“Access element three :” + a[3]); } catch (ArithmeticException e) { System.out.println(“Exception thrown :” + e); }finally { a[0] = 6; System.out.println(“First element value: ” + a[0]); System.out.println(“The finally statement is executed”); } } } Output First element value: 6 The finally statement is executed Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 3 at com.tutorialspoint.ExcepTest.main(ExcepTest.java:8) Example 2 Here is code segment showing how to use finally block where a method can return a value within try block. In this example, we”re returning a value within try block. We can check in output that finally block is printing a statement signifying that finally block is getting executed even after method returned a value to caller function. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { System.out.println(testFinallyBlock()); } private static int testFinallyBlock() { int a[] = new int[2]; try { return 1; } catch (ArrayIndexOutOfBoundsException e) { System.out.println(“Exception thrown :” + e); }finally { a[0] = 6; System.out.println(“First element value: ” + a[0]); System.out.println(“The finally statement is executed”); } return 0; } } Output First element value: 6 The finally statement is executed 1 Print Page Previous Next Advertisements ”;