{"id":1118,"date":"2022-02-07T19:24:24","date_gmt":"2022-02-07T19:24:24","guid":{"rendered":"https:\/\/mdr.foobrdigital.com\/?p=1118"},"modified":"2022-02-07T19:24:24","modified_gmt":"2022-02-07T19:24:24","slug":"files-and-i-o","status":"publish","type":"post","link":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/2022\/02\/07\/files-and-i-o\/","title":{"rendered":"Files and I\/O"},"content":{"rendered":"\n<p>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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"stream\">Stream<\/h2>\n\n\n\n<p>A stream can be defined as a sequence of data. There are two kinds of Streams \u2212<\/p>\n\n\n\n<ul><li><strong>InPutStream<\/strong>&nbsp;\u2212 The InputStream is used to read data from a source.<\/li><li><strong>OutPutStream<\/strong>&nbsp;\u2212 The OutputStream is used for writing data to a destination.<\/li><\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/www.tutorialspoint.com\/java\/images\/streams.png\" alt=\"Streams\"\/><\/figure>\n\n\n\n<p>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 \u2212<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"byte-streams\">Byte Streams<\/h3>\n\n\n\n<p>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,&nbsp;<strong>FileInputStream<\/strong>&nbsp;and&nbsp;<strong>FileOutputStream<\/strong>. Following is an example which makes use of these two classes to copy an input file into an output file \u2212<\/p>\n\n\n\n<p><strong>Example<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.io.*;\npublic class CopyFile {\n\n   public static void main(String args&#91;]) throws IOException {  \n      FileInputStream in = null;\n      FileOutputStream out = null;\n\n      try {\n         in = new FileInputStream(\"input.txt\");\n         out = new FileOutputStream(\"output.txt\");\n         \n         int c;\n         while ((c = in.read()) != -1) {\n            out.write(c);\n         }\n      }finally {\n         if (in != null) {\n            in.close();\n         }\n         if (out != null) {\n            out.close();\n         }\n      }\n   }\n}<\/code><\/pre>\n\n\n\n<p>Now let&#8217;s have a file&nbsp;<strong>input.txt<\/strong>&nbsp;with the following content \u2212<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">This is test for copy file.\n<\/pre>\n\n\n\n<p>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&#8217;s put the above code in CopyFile.java file and do the following \u2212<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">$javac CopyFile.java\n$java CopyFile\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"character-streams\">Character Streams<\/h3>\n\n\n\n<p>Java&nbsp;<strong>Byte<\/strong>&nbsp;streams are used to perform input and output of 8-bit bytes, whereas Java&nbsp;<strong>Character<\/strong>&nbsp;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,&nbsp;<strong>FileReader<\/strong>&nbsp;and&nbsp;<strong>FileWriter<\/strong>. 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.<\/p>\n\n\n\n<p>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 \u2212<\/p>\n\n\n\n<p><strong>Example<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.io.*;\npublic class CopyFile {\n\n   public static void main(String args&#91;]) throws IOException {\n      FileReader in = null;\n      FileWriter out = null;\n\n      try {\n         in = new FileReader(\"input.txt\");\n         out = new FileWriter(\"output.txt\");\n         \n         int c;\n         while ((c = in.read()) != -1) {\n            out.write(c);\n         }\n      }finally {\n         if (in != null) {\n            in.close();\n         }\n         if (out != null) {\n            out.close();\n         }\n      }\n   }\n}<\/code><\/pre>\n\n\n\n<p>Now let&#8217;s have a file&nbsp;<strong>input.txt<\/strong>&nbsp;with the following content \u2212<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">This is test for copy file.\n<\/pre>\n\n\n\n<p>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&#8217;s put the above code in CopyFile.java file and do the following \u2212<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">$javac CopyFile.java\n$java CopyFile\n<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"standard-streams\">Standard Streams<\/h2>\n\n\n\n<p>All the programming languages provide support for standard I\/O where the user&#8217;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 \u2212<\/p>\n\n\n\n<ul><li><strong>Standard Input<\/strong>&nbsp;\u2212 This is used to feed the data to user&#8217;s program and usually a keyboard is used as standard input stream and represented as&nbsp;<strong>System.in<\/strong>.<\/li><li><strong>Standard Output<\/strong>&nbsp;\u2212 This is used to output the data produced by the user&#8217;s program and usually a computer screen is used for standard output stream and represented as&nbsp;<strong>System.out<\/strong>.<\/li><li><strong>Standard Error<\/strong>&nbsp;\u2212 This is used to output the error data produced by the user&#8217;s program and usually a computer screen is used for standard error stream and represented as&nbsp;<strong>System.err<\/strong>.<\/li><\/ul>\n\n\n\n<p>Following is a simple program, which creates&nbsp;<strong>InputStreamReader<\/strong>&nbsp;to read standard input stream until the user types a &#8220;q&#8221; \u2212<\/p>\n\n\n\n<p><strong>Example<\/strong><a href=\"http:\/\/tpcg.io\/lVH2u1\" target=\"_blank\" rel=\"noreferrer noopener\">Live Demo<\/a><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.io.*;\npublic class ReadConsole {\n\n   public static void main(String args&#91;]) throws IOException {\n      InputStreamReader cin = null;\n\n      try {\n         cin = new InputStreamReader(System.in);\n         System.out.println(\"Enter characters, 'q' to quit.\");\n         char c;\n         do {\n            c = (char) cin.read();\n            System.out.print(c);\n         } while(c != 'q');\n      }finally {\n         if (cin != null) {\n            cin.close();\n         }\n      }\n   }\n}<\/code><\/pre>\n\n\n\n<p>Let&#8217;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 &#8216;q&#8217; \u2212<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$javac ReadConsole.java\n$java ReadConsole\nEnter characters, 'q' to quit.\n1\n1\ne\ne\nq\nq\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"reading-and-writing-files\">Reading and Writing Files<\/h2>\n\n\n\n<p>As described earlier, a stream can be defined as a sequence of data. The&nbsp;<strong>InputStream<\/strong>&nbsp;is used to read data from a source and the&nbsp;<strong>OutputStream<\/strong>&nbsp;is used for writing data to a destination.<\/p>\n\n\n\n<p>Here is a hierarchy of classes to deal with Input and Output streams.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/www.tutorialspoint.com\/java\/images\/file_io.jpg\" alt=\"Files IO\"\/><\/figure>\n\n\n\n<p>The two important streams are&nbsp;<strong>FileInputStream<\/strong>&nbsp;and&nbsp;<strong>FileOutputStream<\/strong>, which would be discussed in this tutorial.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"fileinputstream\">FileInputStream<\/h3>\n\n\n\n<p>This stream is used for reading data from the files. Objects can be created using the keyword&nbsp;<strong>new<\/strong>&nbsp;and there are several types of constructors available.<\/p>\n\n\n\n<p>Following constructor takes a file name as a string to create an input stream object to read the file \u2212<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>InputStream f = new FileInputStream(\"C:\/java\/hello\");\n<\/code><\/pre>\n\n\n\n<p>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 \u2212<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>File f = new File(\"C:\/java\/hello\");\nInputStream f = new FileInputStream(f);\n<\/code><\/pre>\n\n\n\n<p>Once you have&nbsp;<em>InputStream<\/em>&nbsp;object in hand, then there is a list of helper methods which can be used to read to stream or to do other operations on the stream.<\/p>\n\n\n\n<figure class=\"wp-block-table is-style-regular\"><table><tbody><tr><th>Sr.No.<\/th><th>Method &amp; Description<\/th><\/tr><tr><td>1<\/td><td><strong>public void close() throws IOException{}<\/strong>This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException.<\/td><\/tr><tr><td>2<\/td><td><strong>protected void finalize()throws IOException {}<\/strong>This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException.<\/td><\/tr><tr><td>3<\/td><td><strong>public int read(int r)throws IOException{}<\/strong>This method reads the specified byte of data from the InputStream. Returns an int. Returns the next byte of data and -1 will be returned if it&#8217;s the end of the file.<\/td><\/tr><tr><td>4<\/td><td><strong>public int read(byte[] r) throws IOException{}<\/strong>This method reads r.length bytes from the input stream into an array. Returns the total number of bytes read. If it is the end of the file, -1 will be returned.<\/td><\/tr><tr><td>5<\/td><td><strong>public int available() throws IOException{}<\/strong>Gives the number of bytes that can be read from this file input stream. Returns an int.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>There are other important input streams available, for more detail you can refer to the following links \u2212<\/p>\n\n\n\n<ul><li>ByteArrayInputStream<\/li><li>DataInputStream<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"fileoutputstream\">FileOutputStream<\/h2>\n\n\n\n<p>FileOutputStream is used to create a file and write data into it. The stream would create a file, if it doesn&#8217;t already exist, before opening it for output.<\/p>\n\n\n\n<p>Here are two constructors which can be used to create a FileOutputStream object.<\/p>\n\n\n\n<p>Following constructor takes a file name as a string to create an input stream object to write the file \u2212<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>OutputStream f = new FileOutputStream(\"C:\/java\/hello\") \n<\/code><\/pre>\n\n\n\n<p>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 \u2212<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>File f = new File(\"C:\/java\/hello\");\nOutputStream f = new FileOutputStream(f);\n<\/code><\/pre>\n\n\n\n<p>Once you have&nbsp;<em>OutputStream<\/em>&nbsp;object in hand, then there is a list of helper methods, which can be used to write to stream or to do other operations on the stream.<\/p>\n\n\n\n<figure class=\"wp-block-table is-style-regular\"><table><tbody><tr><th>Sr.No.<\/th><th>Method &amp; Description<\/th><\/tr><tr><td>1<\/td><td><strong>public void close() throws IOException{}<\/strong>This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException.<\/td><\/tr><tr><td>2<\/td><td><strong>protected void finalize()throws IOException {}<\/strong>This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException.<\/td><\/tr><tr><td>3<\/td><td><strong>public void write(int w)throws IOException{}<\/strong>This methods writes the specified byte to the output stream.<\/td><\/tr><tr><td>4<\/td><td><strong>public void write(byte[] w)<\/strong>Writes w.length bytes from the mentioned byte array to the OutputStream.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>There are other important output streams available, for more detail you can refer to the following links \u2212<\/p>\n\n\n\n<ul><li>ByteArrayOutputStream<\/li><li>DataOutputStream<\/li><\/ul>\n\n\n\n<p><strong>Example<\/strong><\/p>\n\n\n\n<p>Following is the example to demonstrate InputStream and OutputStream \u2212<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.io.*;\npublic class fileStreamTest {\n\n   public static void main(String args&#91;]) {\n   \n      try {\n         byte bWrite &#91;] = {11,21,3,40,5};\n         OutputStream os = new FileOutputStream(\"test.txt\");\n         for(int x = 0; x &lt; bWrite.length ; x++) {\n            os.write( bWrite&#91;x] );   \/\/ writes the bytes\n         }\n         os.close();\n     \n         InputStream is = new FileInputStream(\"test.txt\");\n         int size = is.available();\n\n         for(int i = 0; i &lt; size; i++) {\n            System.out.print((char)is.read() + \"  \");\n         }\n         is.close();\n      } catch (IOException e) {\n         System.out.print(\"Exception\");\n      }\t\n   }\n}<\/code><\/pre>\n\n\n\n<p>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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"file-navigation-and-i-o\">File Navigation and I\/O<\/h2>\n\n\n\n<p>There are several other classes that we would be going through to get to know the basics of File Navigation and I\/O.<\/p>\n\n\n\n<ul><li>File Class<\/li><li>FileReader Class<\/li><li>FileWriter Class<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"directories-in-java\">Directories in Java<\/h2>\n\n\n\n<p>A directory is a File which can contain a list of other files and directories. You use&nbsp;<strong>File<\/strong>&nbsp;object to create directories, to list down files available in a directory. For complete detail, check a list of all the methods which you can call on File object and what are related to directories.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"creating-directories\">Creating Directories<\/h3>\n\n\n\n<p>There are two useful&nbsp;<strong>File<\/strong>&nbsp;utility methods, which can be used to create directories \u2212<\/p>\n\n\n\n<ul><li>The&nbsp;<strong>mkdir( )<\/strong>&nbsp;method creates a directory, returning true on success and false on failure. Failure indicates that the path specified in the File object already exists, or that the directory cannot be created because the entire path does not exist yet.<\/li><li>The&nbsp;<strong>mkdirs()<\/strong>&nbsp;method creates both a directory and all the parents of the directory.<\/li><\/ul>\n\n\n\n<p>Following example creates &#8220;\/tmp\/user\/java\/bin&#8221; directory \u2212<\/p>\n\n\n\n<p><strong>Example<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.io.File;\npublic class CreateDir {\n\n   public static void main(String args&#91;]) {\n      String dirname = \"\/tmp\/user\/java\/bin\";\n      File d = new File(dirname);\n      \n      \/\/ Create directory now.\n      d.mkdirs();\n   }\n}<\/code><\/pre>\n\n\n\n<p>Compile and execute the above code to create &#8220;\/tmp\/user\/java\/bin&#8221;.<\/p>\n\n\n\n<p><strong>Note<\/strong>&nbsp;\u2212 Java automatically takes care of path separators on UNIX and Windows as per conventions. If you use a forward slash (\/) on a Windows version of Java, the path will still resolve correctly.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"listing-directories\">Listing Directories<\/h2>\n\n\n\n<p>You can use&nbsp;<strong>list( )<\/strong>&nbsp;method provided by&nbsp;<strong>File<\/strong>&nbsp;object to list down all the files and directories available in a directory as follows \u2212<\/p>\n\n\n\n<p><strong>Example<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.io.File;\npublic class ReadDir {\n\n   public static void main(String&#91;] args) {\n      File file = null;\n      String&#91;] paths;\n  \n      try {      \n         \/\/ create new file object\n         file = new File(\"\/tmp\");\n\n         \/\/ array of files and directory\n         paths = file.list();\n\n         \/\/ for each name in the path array\n         for(String path:paths) {\n            \/\/ prints filename and directory name\n            System.out.println(path);\n         }\n      } catch (Exception e) {\n         \/\/ if any error occurs\n         e.printStackTrace();\n      }\n   }\n}<\/code><\/pre>\n\n\n\n<p>This will produce the following result based on the directories and files available in your&nbsp;<strong>\/tmp<\/strong>&nbsp;directory \u2212<\/p>\n\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">test1.txt\ntest2.txt\nReadDir.java\nReadDir.class<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>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 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[238],"tags":[],"_links":{"self":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/1118"}],"collection":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/comments?post=1118"}],"version-history":[{"count":0,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/posts\/1118\/revisions"}],"wp:attachment":[{"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/media?parent=1118"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/categories?post=1118"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mudassirbackup.infinitycodestudio.com\/index.php\/wp-json\/wp\/v2\/tags?post=1118"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}