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
Category: Java
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 – Create a File
Java – Creating Files ”; Previous Next Create File in Java We can create a file in Java using multiple ways. Following are three most popular ways to create a file in Java − Using FileOutputStream() constructor Using File.createNewFile() method Using Files.write() method Let”s take a look at each of the way to create file in Java. Create File Using FileOutputStream Constructor FileOutputStream is used to create a file and write data into it. The stream would create a file, if it doesn”t already exist, before opening it for output. Here are two constructors which can be used to create a FileOutputStream object. Following constructor takes a file name as a string to create an input stream object to write the file − Syntax OutputStream f = new FileOutputStream(“C:/java/hello.txt”) Syntax Following constructor takes a file object to create an output stream object to write the file. First, we create a file object using File() method as follows − File f = new File(“C:/java/hello.txt”); OutputStream f = new FileOutputStream(f); Example: Create File Using FileOutputStream Constructor Following is the example to demonstrate FileOutputStream to create a file in current directory− package com.tutorialspoint; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class FileTest { public static void main(String args[]) { try { byte bWrite [] = {65, 66, 67, 68, 69}; OutputStream os = new FileOutputStream(“test.txt”); for(int x = 0; x < bWrite.length ; x++) { os.write( bWrite[x] ); // writes the bytes } os.close(); InputStream is = new FileInputStream(“test.txt”); int size = is.available(); for(int i = 0; i < size; i++) { System.out.print((char)is.read() + ” “); } is.close(); } catch (IOException e) { System.out.print(“Exception”); } } } 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. Output A B C D E Create File Using File.createNewFile() Method File.createNewFile() method allows to create a file in given location or in current directory as follows − Syntax File file = new File(“d://test//testFile1.txt”); //Create the file if (file.createNewFile()) { System.out.println(“File is created!”); } else { System.out.println(“File already exists.”); } Example: Create File Using File.createNewFile() Method Following is the example to demonstrate File to create a file in given directory using createNewFile() method − package com.tutorialspoint; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class FileTest { public static void main(String args[]) { try { File file = new File(“d://test//testFile1.txt”); //Create the file if (file.createNewFile()) { System.out.println(“File is created!”); } else { System.out.println(“File already exists.”); } // Write Content FileWriter writer = new FileWriter(file); writer.write(“Test data”); writer.close(); // read content FileReader reader = new FileReader(file); int c; while ((c = reader.read()) != -1) { char ch = (char) c; System.out.print(ch); } } catch (IOException e) { System.out.print(“Exception”); } } } Output The above code would create file test.txt and would write given string in text format. Same would be the output on the stdout screen. File is created! Test data Create File Using Files.write() Method Files.write() is a newer and more flexible method create a file and write content to a file in same command as shown below − Syntax String data = “Test data”; Files.write(Paths.get(“d://test/testFile3.txt”), data.getBytes()); List<String> lines = Arrays.asList(“1st line”, “2nd line”); Files.write(Paths.get(“file6.txt”), lines, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND); Example: Create File Using Files.write() Method Following is the example to demonstrate File to create a file in given directory using Files.write() method − package com.tutorialspoint; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.List; public class FileTest { public static void main(String args[]) { try { String data = “Test data”; Files.write(Paths.get(“d://test/testFile3.txt”), data.getBytes()); List<String> lines = Arrays.asList(“1st line”, “2nd line”); Files.write(Paths.get( “file6.txt”), lines, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND); List<String> content = Files.readAllLines(Paths.get(“d://test/testFile3.txt”)); System.out.println(content); content = Files.readAllLines(Paths.get(“file6.txt”)); System.out.println(content); } catch (IOException e) { System.out.print(“Exception”); } } } Output The above code would create file test.txt and would write given strings in text format. Same would be the output on the stdout screen. [Test data] [1st line, 2nd line] Print Page Previous Next Advertisements ”;
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 – Exception Propagation
Java – Exception Propagation ”; Previous Next Exception Propagation Exception propagation refers to movement of exception event from nested try or nested methods calls. A try block can be nested within another try block. Similarly a method can call another method where each method can handle exception independently or can throw checked/unchecked exceptions. Whenever an exception is raised within a nested try block/method, its exception is pushed to Stack. The exception propagates from child to parent try block or from child method to parent method and so on. Syntax – Nested Try Block The syntax for nested catch blocks looks like the following − try { // parent try block try { // child try block } catch(ExceptionType1 e1){ // child catch block } } catch (ExceptionType2 e1) { // parent catch block } Syntax – Nested Method Calls The syntax for nested method calls looks like the following − method1(){ // parent method try { // parent try block method2(); } catch (ExceptionType2 e1) { // parent catch block } method2(){ // child method // code to throw Exception // this exception will be handled by parent method } The previous statements demonstrate two try/catch blocks and methods, but you can have any number of them. If an exception occurs in the protected child code, the exception is thrown to the catch block of the child list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes up to the parent catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack. Rules for Exception Propagation in Java Child catch block should have specific exception for better code clarity. Parent catch block can have more generic exception handled so that if child catch block is not able to handle the exception then parent catch block can handle it. There in no restriction on exception hiearchy to be used in child vs parent catch block. If a exception is handled correctly in child catch block, then in parent, another exception can be raised and handled. Java Exception Propagation Example Here is code segment showing exception event propagation from child to parent. In this example, we”re creating an error by dividing a value by 0 in a child method. The child method throws the exception. Now in parent method, in try block, we”re handling the exception and printing the error message. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { int a = 3; int b = 0; try { System.out.println(“result:” + divide(a,b)); }catch(ArithmeticException e) { System.out.println(e.getMessage()); } } private static int divide(int a, int b) { return a / b; } } Output / by zero More Examples Example 1 Here is code segment showing exception event propagation from child to parent. In this example, we”re creating an error by dividing a value by 0 in a child method. The child method throws the exception. Now in parent method, we”re not handling the exception. The JVM will intercept the exception and prints the error message. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { int a = 3; int b = 0; System.out.println(“result:” + divide(a,b)); } private static int divide(int a, int b) { return a / b; } } Output Exception in thread “main” java.lang.ArithmeticException: / by zero at com.tutorialspoint.ExcepTest.divide(ExcepTest.java:12) at com.tutorialspoint.ExcepTest.main(ExcepTest.java:8) Example 2 Here is code segment showing exception event propagation to stop within child itself instead of flowing to parent. In this example, we”re creating an error by dividing a value by 0 in a child method. The child method is handling the exception. Now in parent method, we”re not getting any exception. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { int a = 3; int b = 0; System.out.println(“result:” + divide(a,b)); } private static int divide(int a, int b) { try { return a / b; }catch(ArithmeticException e) { System.out.println(e.getMessage()); } return 0; } } Output / by zero result:0 Print Page Previous Next Advertisements ”;
Java – Encapsulation
Java – Encapsulation ”; Previous Next Java Encapsulation Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction. Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding. Achieving Encapsulation in Java To achieve encapsulation in Java − Declare the variables of a class as private. Provide public setter and getter methods to modify and view the variables values. Java Encapsulation Example Following is an example that demonstrates how to achieve Encapsulation in Java − /* File name : EncapTest.java */ public class EncapTest { private String name; private String idNum; private int age; public int getAge() { return age; } public String getName() { return name; } public String getIdNum() { return idNum; } public void setAge( int newAge) { age = newAge; } public void setName(String newName) { name = newName; } public void setIdNum( String newId) { idNum = newId; } } The public setXXX() and getXXX() methods are the access points of the instance variables of the EncapTest class. Normally, these methods are referred as getters and setters. Therefore, any class that wants to access the variables should access them through these getters and setters. The variables of the EncapTest class can be accessed using the following program − /* File name : RunEncap.java */ public class RunEncap { public static void main(String args[]) { EncapTest encap = new EncapTest(); encap.setName(“James”); encap.setAge(20); encap.setIdNum(“12343ms”); System.out.print(“Name : ” + encap.getName() + ” Age : ” + encap.getAge()); } } public class EncapTest { private String name; private String idNum; private int age; public int getAge() { return age; } public String getName() { return name; } public String getIdNum() { return idNum; } public void setAge( int newAge) { age = newAge; } public void setName(String newName) { name = newName; } public void setIdNum( String newId) { idNum = newId; } } Output Name : James Age : 20 Benefits of Encapsulation The fields of a class can be made read-only or write-only. A class can have total control over what is stored in its fields. Java Encapsulation: Read-Only Class A read-only class can have only getter methods to get the values of the attributes, there should not be any setter method. Example: Creating Read-Only Class In this example, we defined a class Person with two getter methods getName() and getAge(). These methods can be used to get the values of attributes declared as private in the class. // Class “Person” class Person { private String name = “Robert”; private int age = 21; // Getter methods public String getName() { return this.name; } public int getAge() { return this.age; } } public class Main { public static void main(String args[]) { // Object to Person class Person per = new Person(); // Getting and printing the values System.out.println(“Name of the person is: ” + per.getName()); System.out.println(“Age of the person is: ” + per.getAge()); } } Output Name of the person is: Robert Age of the person is: 21 Java Encapsulation: Write-Only Class A write-only class can have only setter methods to set the values of the attributes, there should not be any getter method. Example: Creating Write-Only Class In this example, we defined a class Person with two setter methods setName() and setAge(). These methods can be used to set the values of attributes declared as private in the class. // Class “Person” class Person { private String name; private int age; // Setter Methods public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } } public class Main { public static void main(String args[]) { // Object to Person class Person per = new Person(); // Setting the values per.setName(“Robert”); per.setAge(21); } } Java Encapsulation: More Examples Example 1: Person Class (Fully Encapsulated) This example creates a fully encapsulated class named “Person”. This class has private class attributes, setter, and getter methods. // Class “Person” class Person { private String name; private int age; // Setter Methods public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } // Getter methods public String getName() { return this.name; } public int getAge() { return this.age; } } // The Main class to test encapsulated class “Person” public class Main { public static void main(String args[]) { // Objects to Person class Person per1 = new Person(); Person per2 = new Person(); // Setting the values per1.setName(“Robert”); per1.setAge(21); per2.setName(“Riyan”); per2.setAge(22); // Printing the values System.out.println(“Person 1: Name : ” + per1.getName() + ” Age : ” + per1.getAge()); System.out.println(“Person 2: Name : ” + per2.getName() + ” Age : ” + per2.getAge()); } } Output Person 1: Name : Robert Age : 21 Person 2: Name : Riyan Age : 22 Example 2: Employee Class (Fully Encapsulated) This example creates a fully encapsulated class named “Employee”. This class has private class attributes, setter, and getter methods. // Class “Employee” class Employee { private String emp_name; private String emp_id; private double net_salary; // Constructor public Employee(String emp_name, String emp_id, double net_salary) { this.emp_name = emp_name; this.emp_id = emp_id; this.net_salary = net_salary; } // Getter methods public String getEmpName() { return emp_name; } public String getEmpId() { return emp_id; } public double getSalary() { return net_salary; } // Setter methods public void setEmpName(String emp_name) { this.emp_name = emp_name; } public void setEmpId(String emp_id) { this.emp_id = emp_id; } public void setSalary(double net_salary) { this.net_salary = net_salary; } } // The Main class to test encapsulated class “Employee” public class Main { public static void main(String args[]) { // Objects to Employee class // First object – setting values using constructor Employee emp = new Employee(“Robert”, “EMP001”, 75450.00);