<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Ankit Virparia &#187; Java Tutorials</title>
	<atom:link href="http://ankit.co/category/tutorials/java-tutorials/feed" rel="self" type="application/rss+xml" />
	<link>http://ankit.co</link>
	<description>A Programmer, Designer and Trainer</description>
	<lastBuildDate>Sun, 11 May 2014 04:15:47 +0000</lastBuildDate>
	<language>en-US</language>
		<sy:updatePeriod>hourly</sy:updatePeriod>
		<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.0.38</generator>
	<item>
		<title>Testing Random Execution &#8211; Java Multithreading</title>
		<link>http://ankit.co/tutorials/java-tutorials/multithreading/testing-random-execution-java-multithreading?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=testing-random-execution-java-multithreading</link>
		<comments>http://ankit.co/tutorials/java-tutorials/multithreading/testing-random-execution-java-multithreading#comments</comments>
		<pubDate>Tue, 05 Feb 2013 08:57:18 +0000</pubDate>
		<dc:creator><![CDATA[Ankit Virparia]]></dc:creator>
				<category><![CDATA[Multithreading]]></category>

		<guid isPermaLink="false">http://ankit.co/?p=619</guid>
		<description><![CDATA[<p>Random Execution Multithreading is used to divide a program in to several parts which can be executed in parallel. Java supports multithreading which is absolutely true but Java as a programming language cannot execute the instruction in microprocessor in parallel(by switching). Java relies on operating system for that. So, what we are going to prove [&#8230;]</p>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/multithreading/testing-random-execution-java-multithreading">Testing Random Execution &#8211; Java Multithreading</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></description>
				<content:encoded><![CDATA[<h2>Random Execution</h2>
<p>Multithreading is used to divide a program in to several parts which can be executed in parallel. Java supports multithreading which is absolutely true but Java as a programming language cannot execute the instruction in microprocessor in parallel(by switching). Java relies on operating system for that. So, what we are going to prove here is: Execution/Switching of the threads are done by Operation System at run time. So there will be random execution sequence for us every time we run the program. You can see the output displayed below:</p>
<pre class="brush: java; title: ; notranslate">
class RandomExecution implements Runnable
{
	Thread t;
	RandomExecution()
	{
		t = new Thread(this);
		t.start();
		for(int i=0;i&lt;10;i++)
		{
			System.out.println(&quot;Parent:&quot;+i);	
		}	
			
	}
	public static void main(String[] s)
	{
		RandomExecution obj = new RandomExecution();	
	}	
	public void run()
	{
		for(int i=0;i&lt;10;i++)
		{
			System.out.println(&quot;Run:&quot;+i);	
		}	
	}
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/RandomExecution.jpg" rel="attachment"><img class="size-full aligncenter" alt="Random printing example" src="../../../images/RandomExecution_400.jpg" /></a><br />
<br/></p>
<hr/>
<br/><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/RandomExecution2.jpg" rel="attachment"><img class="size-full aligncenter" alt="Random printing example" src="../../../images/RandomExecution2_400.jpg" /></a></p>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/multithreading/testing-random-execution-java-multithreading">Testing Random Execution &#8211; Java Multithreading</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://ankit.co/tutorials/java-tutorials/multithreading/testing-random-execution-java-multithreading/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Random Access File &#8211; Java</title>
		<link>http://ankit.co/tutorials/java-tutorials/input-output/random-access-file-java?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=random-access-file-java</link>
		<comments>http://ankit.co/tutorials/java-tutorials/input-output/random-access-file-java#comments</comments>
		<pubDate>Wed, 23 Jan 2013 03:58:28 +0000</pubDate>
		<dc:creator><![CDATA[Ankit Virparia]]></dc:creator>
				<category><![CDATA[Input Output]]></category>
		<category><![CDATA[IO]]></category>
		<category><![CDATA[RAF]]></category>

		<guid isPermaLink="false">http://ankit.co/?p=595</guid>
		<description><![CDATA[<p>Java supports a file reading writing mechanism which is allows us to manipulate data at any specific location of the file. A random access file works like an array of bytes. It do not create an array in the memory. It just treat file as a byte array and maintain the current index of the [&#8230;]</p>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/input-output/random-access-file-java">Random Access File &#8211; Java</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></description>
				<content:encoded><![CDATA[<p>Java supports a file reading writing mechanism which is allows us to manipulate data at any specific location of the file. A random access file works like an array of bytes. It do not create an array in the memory. It just treat file as a byte array and maintain the current index of the same. So that we can read or write from the specific location that is also called as file pointer. There are various ways to create an object of java.io.RandomAccessFile class. If the object is created in read/write mode, then write operations are also allowed. The file pointer can be read by the getFilePointer method and set by the seek method.</p>
<p><strong>Important Points:</strong></p>
<ul>
<li>RandomAccessFile manages a file pointer</li>
<li>On creating the object, It points to the 1st byte of the file</li>
<li>On trying to skip bytes which are even more than the file size, it will reach to end of the file.</li>
</ul>
<h3>Constructor Summary</h3>
<p>public RandomAccessFile (File file, String mode) throws FileNotFoundException<br />
public RandomAccessFile (String filePath, String mode) throws FileNotFoundException</p>
<h3>RandomAccessFile Modes</h3>
<pre class="brush: java; title: ; notranslate">
&quot;r&quot;	  Open for reading only. Invoking any of the write methods of the resulting object will cause an IOException to be thrown.
&quot;rw&quot;  Open for reading and writing. If the file does not already exist then an attempt will be made to create it.
&quot;rws&quot; Open for reading and writing, as with &quot;rw&quot;, and also require that every update to the file's content or metadata be written synchronously to the underlying storage device.
&quot;rwd&quot; Open for reading and writing, as with &quot;rw&quot;, and also require that every update to the file's content be written synchronously to the underlying storage device.
</pre>
<h3>Program:</h3>
<p><strong>Aim:</strong> Write a program using RandomAccessFile class to write 4 int values in a file. Access the 3rd int from the file and change its value by another.</p>
<pre class="brush: java; title: ; notranslate">
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessDemo 
{
  public static void main(String[] args) 
  {
    try 
	{		
      RandomAccessFile raf = new RandomAccessFile(&quot;test.txt&quot;, &quot;rw&quot;);
      raf.writeInt(10);
      raf.writeInt(20);
      raf.writeInt(30);
      raf.writeInt(400);

      raf.seek((3 - 1) * 4);  // For 3rd integer, We are doing 2 * size of Int(4).

      raf.writeInt(99);

      raf.seek(0);   // Going back to start point
      
      int i = 0;
      while(raf.length()&gt;raf.getFilePointer()) 
      {
		i = raf.readInt();
        System.out.println(i);
      }
      raf.close();
    } 
	catch (Exception e) 
	{
		System.out.println(e);
    }
  }
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/RandomAccessDemo.jpg" rel="attachment"><img class="size-full aligncenter" alt="Random Access File example" src="../../../images/RandomAccessDemo_400.jpg" /></a></p>
<hr/>
<p><strong>Aim:</strong> Write a program using RandomAccessFile class to append an existing file (Generated by above program).</p>
<pre class="brush: java; title: ; notranslate">
import java.io.File;
import java.io.RandomAccessFile;

public class RAFAppendDemo 
{
  public static void main(String[] args) throws Exception 
  {
    File f = new File(&quot;test.txt&quot;);
    long fileLength = f.length();
    RandomAccessFile raf = new RandomAccessFile(f, &quot;rw&quot;);
    raf.seek(fileLength);
    raf.writeBytes(&quot;Appended text\n&quot;);
  
    raf.seek(0);
	
	System.out.println(raf.readInt());  
	System.out.println(raf.readInt());  
	System.out.println(raf.readInt());  
	System.out.println(raf.readInt());  
	System.out.println(raf.readLine());  
  
    raf.close();
  
  }
  
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/RAFAppendDemo.jpg" rel="attachment"><img class="size-full aligncenter" alt="Random Access File" src="../../../images/RAFAppendDemo_400.jpg" /></a></p>
<hr/>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/input-output/random-access-file-java">Random Access File &#8211; Java</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://ankit.co/tutorials/java-tutorials/input-output/random-access-file-java/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Various ways to read a file</title>
		<link>http://ankit.co/tutorials/java-tutorials/input-output/various-ways-to-read-a-file?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=various-ways-to-read-a-file</link>
		<comments>http://ankit.co/tutorials/java-tutorials/input-output/various-ways-to-read-a-file#comments</comments>
		<pubDate>Thu, 17 Jan 2013 07:22:16 +0000</pubDate>
		<dc:creator><![CDATA[Ankit Virparia]]></dc:creator>
				<category><![CDATA[Input Output]]></category>
		<category><![CDATA[File]]></category>
		<category><![CDATA[IO]]></category>

		<guid isPermaLink="false">http://ankit.co/?p=566</guid>
		<description><![CDATA[<p>Persistence vs Permanent storage In programming, persistence storage refers to a storage area which may forget the data/information once it looses the electronic energy supply. such as RAM &#8211; Random Access Memory. When we run an application having some variables, methods, objects, etc. That data is stored in Computer RAM. Problem with this system is [&#8230;]</p>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/input-output/various-ways-to-read-a-file">Various ways to read a file</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></description>
				<content:encoded><![CDATA[<h2>Persistence vs Permanent storage</h2>
<p>In programming, persistence storage refers to a storage area which may forget the data/information once it looses the electronic energy supply. such as RAM &#8211; Random Access Memory. When we run an application having some variables, methods, objects, etc. That data is stored in Computer RAM. Problem with this system is when we want to share some information between two execution cycle that won&#8217;t be possible. For Example: We have developed a &#8220;Student Management System&#8221; for a college and one operator starts entering student records in our software. If we as a developer has written code which stores student information in an Array, in that case a power failure/system crash/software termination/software closing may lead to information lost and operator need to start entering details from the scratch! Here the conclusion is: We cannot not store the important or permanent data in RAM. We must choose either 1) File 2) Database. In this tutorial we gonna learn about reading a file. so that the previously written data can be fetched and processed. By this way our application will also be in a consistent state. Following are the various ways to read a file in any storage device like hard disk, floppy, pen drive, etc. The basic need to use a storage device is to mount the same and you are ready to go!</p>
<h2>FileInputStream</h2>
<p>FileInputStream is derived from InputStream class.</p>
<pre class="brush: java; title: ; notranslate">
import java.io.*;

class FileInputStreamDemo
{
	public static void main(String[] s)throws IOException
	{
		byte[] b = new byte[10000];
		File f = new File(&quot;data.txt&quot;);  // this wil points to the data.txt of the same directory where your program is stored.
		FileInputStream fis = new FileInputStream(f);
		int length = fis.read(b);
		String str = new String(b,0,length);
		
		System.out.println(&quot;Data: &quot;+str);
		
		fis.close();
			
	}	
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/FileInputStreamDemo.jpg" rel="attachment"><img class="size-full aligncenter" alt="File Input Stream example" src="../../../images/FileInputStreamDemo_400.jpg" /></a></p>
<hr/>
<h2>FileReader</h2>
<pre class="brush: java; title: ; notranslate">
import java.io.*;

class FileReaderDemo
{
	public static void main(String[] s)throws IOException
	{
		String str = &quot;&quot;;
		char[] c = new char[100];
		File f = new File(&quot;data.txt&quot;); 
		FileReader fr = new FileReader(f);
		
		int len = 0;
		len = fr.read(c);
		str = new String(c,0,len);
		System.out.println(&quot;Data: &quot;+str);
		
		fr.close();
	}	
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/FileReaderDemo.jpg" rel="attachment"><img class="size-full aligncenter" alt="File Reader example" src="../../../images/FileReaderDemo_400.jpg" /></a></p>
<hr/>
<h2>BufferedWriter + FileWriter</h2>
<pre class="brush: java; title: ; notranslate">
import java.io.*;

class FileBufferedReaderDemo
{
	public static void main(String[] arg)throws Exception
	{
		BufferedReader br = new BufferedReader(new FileReader(new File(&quot;data.txt&quot;)));
		System.out.print(&quot;Data: &quot;);
		String str = br.readLine();
		System.out.println(str);	
	}
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/FileBufferedReaderDemo.jpg" rel="attachment"><img class="size-full aligncenter" alt="Buffered Reader file example" src="../../../images/FileBufferedReaderDemo_400.jpg" /></a></p>
<hr/>
<h2>FilterReader</h2>
<p>FilterReader is an abstract class which does not have any abstract method. We can override the methods of it and perform our code instead. For more details visit: <a href="tutorials/java-tutorials/input-output/filterreader" title="FilterReader">FilterReader</a></p>
<h3>Aim</h3>
<p>Write a program using FilterReader which removes tags from the file content. e.g. &lt;tag&gt; should be removed.</p>
<pre class="brush: java; title: ; notranslate">

import java.io.*;
class FilterReaderDemo
{
  	public static void main(String[] args) 
	{
		try 
		{
          FilterReader fr = new FilterReader(new FileReader(&quot;data.txt&quot;)){
			  		  public int read(char[] buf, int from, int len) throws IOException 
					  {
						boolean intag = false;
						int numchars = 0; 
						
						while (numchars == 0) 
						{
						  numchars = in.read(buf, from, len); 
						  if (numchars == -1)
						  {
							return -1;
						  }
						  int last = from; 
						  for (int i = from; i &lt; from + numchars; i++) 
						  {
							if (!intag) 
							{
							  if (buf[i] == '&lt;')
								intag = true; 
							  else
								buf[last++] = buf[i]; 
							} 
							else if (buf[i] == '&gt;')
							{
							  intag = false;
							}
						  }
						  numchars = last - from; 
						}
						return numchars;
					  }
					
					  public int read() throws IOException 
					  {
						char[] buf = new char[1];
						int result = read(buf, 0, 1);
						if (result == -1)
						  return -1;
						else
						  return (int) buf[0];
					  }
			  };
		  BufferedReader in = new BufferedReader(fr);
		  
		  String line;
		  while ((line = in.readLine()) != null)
		  {
			System.out.println(line);
		  }
		  in.close(); // Close the stream.
		} 
		catch (Exception e) 
		{
		  System.err.println(e);
		}
  }
}

</pre>
<p><strong>Output:</strong><br />
<strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/FilterDemo.jpg" rel="attachment"><img class="size-full aligncenter" alt="Filter Demo" src="../../../images/FilterDemo_400.jpg" /></a><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/FilterDemoOutput.jpg" rel="attachment"><img class="size-full aligncenter" alt="BufferedWriter demo" src="../../../images/FilterDemoOutput_400.jpg" /></a></p>
<hr/>
<h2>DataInputStream</h2>
<pre class="brush: java; title: ; notranslate">
import java.io.*;
class DataInputStreamDemo
{
	public static void main(String[] s)throws Exception
	{
		FileInputStream fis = new FileInputStream(new File(&quot;db.txt&quot;));
		DataInputStream dis = new DataInputStream(fis);
		int avail =  dis.available();
		byte[] b = new byte[avail];
		dis.readFully(b);
		System.out.println(new String(b)); 
		dis.close();		
	}	
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/DataInputStreamDemo.jpg" rel="attachment"><img class="size-full aligncenter" alt="Data Input StreamDemo" src="../../../images/DataInputStreamDemo_400.jpg" /></a></p>
<hr/>
<h2>ObjectInputStream</h2>
<pre class="brush: java; title: ; notranslate">
import java.io.*;
import java.util.*;
class ObjectInputStreamDemo
{
	public static void main(String[] s)throws Exception
	{
		FileInputStream fis = new FileInputStream(&quot;test.txt&quot;);
        ObjectInputStream ois = new ObjectInputStream(fis);

        System.out.println(ois.readInt());
        System.out.println(ois.readObject());
        System.out.println(ois.readObject());
		ois.close();
		System.out.println(&quot;All Objects read!&quot;);
	}	
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/ObjectInputStreamDemo.jpg" rel="attachment"><img class="size-full aligncenter" alt="Object Input Demo" src="../../../images/ObjectInputStreamDemo_400.jpg" /></a></p>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/input-output/various-ways-to-read-a-file">Various ways to read a file</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://ankit.co/tutorials/java-tutorials/input-output/various-ways-to-read-a-file/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>FilterReader</title>
		<link>http://ankit.co/tutorials/java-tutorials/input-output/filterreader?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=filterreader</link>
		<comments>http://ankit.co/tutorials/java-tutorials/input-output/filterreader#comments</comments>
		<pubDate>Thu, 17 Jan 2013 06:07:58 +0000</pubDate>
		<dc:creator><![CDATA[Ankit Virparia]]></dc:creator>
				<category><![CDATA[Input Output]]></category>
		<category><![CDATA[File]]></category>
		<category><![CDATA[IO]]></category>

		<guid isPermaLink="false">http://ankit.co/?p=567</guid>
		<description><![CDATA[<p>What is Filtering? A normal reader/writer class can read/write what we demand for. But lets say we have a special requirement of writing/reading. For Example: We want to read only those lines from the file which has &#8220;.&#8221; at the end. Rest we want to skip. For this kind of scenario where by some very [&#8230;]</p>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/input-output/filterreader">FilterReader</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></description>
				<content:encoded><![CDATA[<h2>What is Filtering?</h2>
<p>A normal reader/writer class can read/write what we demand for. But lets say we have a special requirement of writing/reading. For Example: We want to read only those lines from the file which has &#8220;.&#8221; at the end. Rest we want to skip. For this kind of scenario where by some very frequent and static processing is to be done each time then we can create our own FilterReader which will do the job for us. So that manually we will not be doing it again and again. FilterReader is an abstract class which does not have any abstract method. We can override the methods of it and perform our code instead. We are going to discuss another case here.</p>
<h3>Aim</h3>
<p>Write a program using FilterReader which removes tags from the file content. e.g. &lt;tag&gt; should be removed.</p>
<pre class="brush: java; title: ; notranslate">
import java.io.*;

class NoTagReader extends FilterReader 
{
  boolean intag = false;
  public NoTagReader(Reader r) 
  {
    super(r);
  }

  public int read(char[] buf, int from, int len) throws IOException 
  {
    int numchars = 0; 
	
    while (numchars == 0) 
	{
      numchars = in.read(buf, from, len); 
      if (numchars == -1)
	  {
        return -1;
	  }
      int last = from; 
      for (int i = from; i &lt; from + numchars; i++) 
	  {
        if (!intag) 
		{
          if (buf[i] == '&lt;')
            intag = true; 
          else
            buf[last++] = buf[i]; 
        } 
		else if (buf[i] == '&gt;')
		{
          intag = false;
		}
      }
      numchars = last - from; 
    }
    return numchars;
  }

  public int read() throws IOException 
  {
    char[] buf = new char[1];
    int result = read(buf, 0, 1);
    if (result == -1)
      return -1;
    else
      return (int) buf[0];
  }

}
class FilterReaderDemo
{
  	public static void main(String[] args) 
	{
		try 
		{
          NoTagReader ntr = new NoTagReader(new FileReader(&quot;data.txt&quot;))
		  BufferedReader in = new BufferedReader(ntr);
		  
		  String line;
		  while ((line = in.readLine()) != null)
		  {
			System.out.println(line);
		  }
		  in.close(); // Close the stream.
		} 
		catch (Exception e) 
		{
		  System.err.println(e);
		}
  }
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/FilterReaderDemo.jpg" rel="attachment"><img class="size-full aligncenter" alt="Filter Reader Demo" src="../../../images/FilterReaderDemo_400.jpg" /></a><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/FilterRaderDemo_output.jpg" rel="attachment"><img class="size-full aligncenter" alt="Filter Reader demo" src="../../../images/FilterRaderDemo_output_400.jpg" /></a></p>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/input-output/filterreader">FilterReader</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://ankit.co/tutorials/java-tutorials/input-output/filterreader/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>FilterWriter</title>
		<link>http://ankit.co/tutorials/java-tutorials/input-output/filterwriter?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=filterwriter</link>
		<comments>http://ankit.co/tutorials/java-tutorials/input-output/filterwriter#comments</comments>
		<pubDate>Wed, 16 Jan 2013 08:27:51 +0000</pubDate>
		<dc:creator><![CDATA[Ankit Virparia]]></dc:creator>
				<category><![CDATA[Input Output]]></category>
		<category><![CDATA[File]]></category>
		<category><![CDATA[Filter]]></category>
		<category><![CDATA[IO]]></category>

		<guid isPermaLink="false">http://ankit.co/?p=556</guid>
		<description><![CDATA[<p>What is Filtering? A normal reader/writer class can read/write what we demand for. But lets say we have a special requirement of writing/reading. For Example: At the end of the file which we write, we want to print(write) Date. Which is a special requirement and this will be needed for each time we write a [&#8230;]</p>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/input-output/filterwriter">FilterWriter</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></description>
				<content:encoded><![CDATA[<h2>What is Filtering?</h2>
<p>A normal reader/writer class can read/write what we demand for. But lets say we have a special requirement of writing/reading. For Example: At the end of the file which we write, we want to print(write) Date. Which is a special requirement and this will be needed for each time we write a file. For this kind of scenario where by some very frequent and static processing is to be done each time then we can create our own FilterWriter which will do the job for us. So that manually we will not be doing it again and again. FilterWriter is an abstract class which does not have any abstract method. We can override the methods of it and perform our code instead. We are going to discuss another case here.</p>
<h3>Aim</h3>
<p>Write a program using FilterWriter which converts larges statements(having more than 15 chars) to  a shorter statement and write a file.<br />
e.g. If we tries to write &#8220;This is demo by Ankit&#8221;. It appends first 5 chars and last 5 chars of string with &#8220;&#8230;&#8221; and generate &#8220;This &#8230; Ankit&#8221; as a output.</p>
<pre class="brush: java; title: ; notranslate">
import java.io.*;

public class FilterDemo 
{

    public static void main(String[] args)throws Exception
	{
        File f = new File(&quot;data.txt&quot;);  
		FileWriter fw = new FileWriter(f);
		myFilterWriter mfw = new myFilterWriter(fw);
		mfw.write(&quot;This is demo by Ankit&quot;);
		mfw.flush();
		mfw.close();
    }
}

class myFilterWriter extends FilterWriter
{
    myFilterWriter(Writer w)
    {
       super(w); 
    }

    @Override
    public void write(String str) throws IOException 
    {
        int len = str.length();
        String output = &quot;&quot;;
        if(len&gt;15)
        {
            output = str.substring(0,5);
            output += &quot;... &quot;;
            output += str.substring(len-5,len);
        }
        super.write(output); 
    }
    
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/FilterDemo.jpg" rel="attachment"><img class="size-full aligncenter" alt="Filter Demo" src="../../../images/FilterDemo_400.jpg" /></a><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/FilterDemoOutput.jpg" rel="attachment"><img class="size-full aligncenter" alt="BufferedWriter demo" src="../../../images/FilterDemoOutput_400.jpg" /></a></p>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/input-output/filterwriter">FilterWriter</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://ankit.co/tutorials/java-tutorials/input-output/filterwriter/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Various ways to write a file</title>
		<link>http://ankit.co/tutorials/java-tutorials/input-output/various-ways-to-write-a-file?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=various-ways-to-write-a-file</link>
		<comments>http://ankit.co/tutorials/java-tutorials/input-output/various-ways-to-write-a-file#comments</comments>
		<pubDate>Wed, 16 Jan 2013 05:14:54 +0000</pubDate>
		<dc:creator><![CDATA[Ankit Virparia]]></dc:creator>
				<category><![CDATA[Input Output]]></category>
		<category><![CDATA[File]]></category>
		<category><![CDATA[IO]]></category>

		<guid isPermaLink="false">http://ankit.co/?p=550</guid>
		<description><![CDATA[<p>Persistence vs Permanent storage In programming, persistence storage refers to a storage area which may forget the data/information once it looses the electronic energy supply. such as RAM &#8211; Random Access Memory. When we run an application having some variables, methods, objects, etc. That data is stored in Computer RAM. Problem with this system is [&#8230;]</p>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/input-output/various-ways-to-write-a-file">Various ways to write a file</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></description>
				<content:encoded><![CDATA[<h2>Persistence vs Permanent storage</h2>
<p>In programming, persistence storage refers to a storage area which may forget the data/information once it looses the electronic energy supply. such as RAM &#8211; Random Access Memory. When we run an application having some variables, methods, objects, etc. That data is stored in Computer RAM. Problem with this system is when we want to share some information between two execution cycle that won&#8217;t be possible. For Example: We have developed a &#8220;Student Management System&#8221; for a college and one operator starts entering student records in our software. If we as a developer has written code which stores student information in an Array, in that case a power failure/system crash/software termination/software closing may lead to information lost and operator need to start entering details from the scratch! Here the conclusion is: We cannot not store the important or permanent data in RAM. We must choose either 1) File 2) Database. In this tutorial we gonna learn about writing a file. so that the same/other application can read the data which we have written in future. By this way our application will also be in a consistent state. Following are the various ways to write a file in any storage device like hard disk, floppy, pen drive, etc. The basic need to use a storage device is to mount the same and you are ready to go!</p>
<h2>FileOutputStream</h2>
<p>FileOutputStream is derived from OutputStream class.</p>
<pre class="brush: java; title: ; notranslate">
import java.io.*;

class FileOutputStreamDemo
{
	public static void main(String[] s)throws IOException
	{
		byte[] b;
		String str = &quot;I want to write some text to file.&quot;;
		b = str.getBytes();
		
		
		File f = new File(&quot;data.txt&quot;);  // this will points to the data.txt of the same directory where your program is stored.
		FileOutputStream fos = new FileOutputStream(f);
		fos.write(b);
		fos.flush();
		
		System.out.println(&quot;File Created!&quot;);
		
		fos.close();
	}	
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/FileOutputStreamDemoOutput.jpg" rel="attachment"><img class="size-full aligncenter" alt="File Output Stream example" src="../../../images/FileOutputStreamDemoOutput_400.jpg" /></a><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/FileOutputStreamDemo.jpg" rel="attachment"><img class="size-full aligncenter" alt="File Output Stream demo" src="../../../images/FileOutputStreamDemo_400.jpg" /></a></p>
<hr/>
<h2>FileWriter</h2>
<pre class="brush: java; title: ; notranslate">
import java.io.*;

class FileWriterDemo
{
	public static void main(String[] s)throws IOException
	{
		String str = &quot;I want to write some text to file.&quot;;
		
		File f = new File(&quot;data.txt&quot;);  // this wil points to the data.txt of the same directory where your program is stored.
		FileWriter fw = new FileWriter(f);
		
		fw.write(str);
		fw.flush();
		
		System.out.println(&quot;File Created!&quot;);
		
		fw.close();
	}	
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/FileOutputStreamDemoOutput.jpg" rel="attachment"><img class="size-full aligncenter" alt="File Writer example" src="../../../images/FileOutputStreamDemoOutput_400.jpg" /></a><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/FileWriter.jpg" rel="attachment"><img class="size-full aligncenter" alt="File Writer demo" src="../../../images/FileWriter_400.jpg" /></a></p>
<hr/>
<h2>BufferedWriter + FileWriter</h2>
<pre class="brush: java; title: ; notranslate">
import java.io.*;

class FileBufferedWriterDemo
{
	public static void main(String[] s)throws IOException
	{
		String str = &quot;I want to write some text to file.&quot;;
		
		
		File f = new File(&quot;data.txt&quot;);  // this wil points to the data.txt of the same directory where your program is stored.
		FileWriter fw = new FileWriter(f);
		BufferedWriter bw = new BufferedWriter(fw);
		
		bw.write(str);
		bw.flush();
		
		System.out.println(&quot;File Created!&quot;);
		
		bw.close();
			
	}	
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/FileOutputStreamDemoOutput.jpg" rel="attachment"><img class="size-full aligncenter" alt="Buffered Writer file example" src="../../../images/FileOutputStreamDemoOutput_400.jpg" /></a><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/FileBufferedWriterDemo.jpg" rel="attachment"><img class="size-full aligncenter" alt="BufferedWriter demo" src="../../../images/FileBufferedWriterDemo_400.jpg" /></a></p>
<hr/>
<h2>FilterWriter</h2>
<p>FilterWriter is an abstract class which does not have any abstract method. We can override the methods of it and perform our code instead. For more details visit: <a href="tutorials/java-tutorials/input-output/filterwriter" title="FilterWriter">FilterWriter</a></p>
<h3>Aim</h3>
<p>Write a program which defines a FilterWriter which converts larges statements(having more than 15 chars) to  a shorter statement and write a file.<br />
e.g. If we tries to write &#8220;This is demo by Ankit&#8221;. It appends first 5 chars and last 5 chars of string with &#8220;&#8230;&#8221; and generate &#8220;This &#8230; Ankit&#8221; as a output.</p>
<pre class="brush: java; title: ; notranslate">
import java.io.*;
public class FilterDemo
{
    public static void main(String[] args) throws IOException 
    {
        // TODO code application logic here
        File f = new File(&quot;data.txt&quot;);  
        FileWriter fw = new FileWriter(f);
        FilterWriter mfw = new FilterWriter(fw){
            @Override
            public void write(String str) throws IOException 
            {
                int len = str.length();
                String output = &quot;&quot;;
                if(len&gt;15)
                {
                    output = str.substring(0,5);
                    output += &quot;... &quot;;
                    output += str.substring(len-5,len);
                }
                super.write(output); 
             }};
        mfw.write(&quot;This is demo by Ankit&quot;);
        mfw.flush();
        mfw.close();
        
    }
}

</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/FilterDemo.jpg" rel="attachment"><img class="size-full aligncenter" alt="Filter Demo" src="../../../images/FilterDemo_400.jpg" /></a><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/FilterDemoOutput.jpg" rel="attachment"><img class="size-full aligncenter" alt="BufferedWriter demo" src="../../../images/FilterDemoOutput_400.jpg" /></a></p>
<hr/>
<h2>DataOputputStream</h2>
<pre class="brush: java; title: ; notranslate">
import java.io.*;
class DataOutputStreamDemo
{
	public static void main(String[] s)throws Exception
	{
		FileOutputStream fos = new FileOutputStream(new File(&quot;db.txt&quot;));
		DataOutputStream dos = new DataOutputStream(fos);
		dos.writeBytes(&quot;This is Test\n\n&quot;); 
		dos.writeDouble(1232.23);
		dos.writeInt(123);
		
		dos.flush();
		dos.close();	
		System.out.println(&quot;File Written&quot;);	
	}	
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/DataOutputStreamDemo.jpg" rel="attachment"><img class="size-full aligncenter" alt="Filter Demo" src="../../../images/DataOutputStreamDemo_400.jpg" /></a></p>
<hr/>
<h2>ObjectOputputStream</h2>
<pre class="brush: java; title: ; notranslate">
import java.io.*;
import java.util.*;
class ObjectOutputStreamDemo
{
	public static void main(String[] s)throws Exception
	{
		FileOutputStream fos = new FileOutputStream(&quot;test.txt&quot;);
                ObjectOutputStream oos = new ObjectOutputStream(fos);

                oos.writeInt(12345);
                oos.writeObject(&quot;Today&quot;);
                oos.writeObject(new Date());
		oos.flush();
                oos.close();
		System.out.println(&quot;Objects written!&quot;);
	}	
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/OOS.jpg" rel="attachment"><img class="size-full aligncenter" alt="Object Output Demo" src="../../../images/OOS_400.jpg" /></a></p>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/input-output/various-ways-to-write-a-file">Various ways to write a file</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://ankit.co/tutorials/java-tutorials/input-output/various-ways-to-write-a-file/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Various ways to write on Console</title>
		<link>http://ankit.co/tutorials/java-tutorials/input-output/various-ways-to-write-on-console?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=various-ways-to-write-on-console</link>
		<comments>http://ankit.co/tutorials/java-tutorials/input-output/various-ways-to-write-on-console#comments</comments>
		<pubDate>Wed, 16 Jan 2013 00:57:57 +0000</pubDate>
		<dc:creator><![CDATA[Ankit Virparia]]></dc:creator>
				<category><![CDATA[Input Output]]></category>
		<category><![CDATA[Console]]></category>
		<category><![CDATA[IO]]></category>

		<guid isPermaLink="false">http://ankit.co/?p=536</guid>
		<description><![CDATA[<p>When we launch an application using java.exe using command prompt at that time, cmd.exe will be our parent application. So, in this tutorial we gonna learn various techniques to send some data to parent(command prompt) application. A stream object is available with us by default which is named as: System.out where by System is the [&#8230;]</p>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/input-output/various-ways-to-write-on-console">Various ways to write on Console</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></description>
				<content:encoded><![CDATA[<p>When we launch an application using java.exe using command prompt at that time, cmd.exe will be our parent application. So, in this tutorial we gonna learn various techniques to send some data to parent(command prompt) application. A stream object is available with us by default which is named as: <strong>System.out</strong> where by System is the class of java.lang package.</p>
<p>System.out is the object of java.io.PrintStream class. And it&#8217;s capable enough to send any kind of data to console or File. So in most of the case we don&#8217;t go for any other option. But still as a part of &#8220;Various ways to write on console&#8221;, we gonna discuss several method of writing data on console/command prompt. You can see the <a href="http://docs.ankit.co/api/java/io/PrintStream.html" title="Javadoc PrintStream">list of methods here</a>.</p>
<h2>PrintStream &#8211; System.out</h2>
<pre class="brush: java; title: ; notranslate">
import java.util.*;
class SODemo
{
	public static void main(String[] s)
	{
		System.out.println(1);  // println(int)
		System.out.println(1.2f);  // println(float)
		System.out.println(1.2);  // println(double)
		System.out.println(&quot;Ankit&quot;);  // println(String)
		System.out.println('c');  // println(char)
		System.out.println(new Date());  // println(Object)
		System.out.println(new myOPClass(9));  // println(Object)	
	}
}

class myOPClass
{
	int x = 0;
	myOPClass(int x)
	{
		this.x = x;	
	}
	public String toString()
	{
		return &quot;Value of X: &quot;+x;	
	}	
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/SODemo.jpg" rel="attachment"><img class="size-full aligncenter" alt="System out example" src="../../../images/SODemo_400.jpg" /></a></p>
<p><strong>Note: </strong>PrintStream is derived from OutputStream class of java.io package. PrintStream is a Filtered Output Stream.</p>
<hr/>
<h2>OutputStream + System.out</h2>
<p>As discussed, OutputStream is the parent class of PrintStream. So a object of PrintStream class can be referenced by OutputStream.</p>
<pre class="brush: java; title: ; notranslate">
import java.io.*;
class OSDemo
{
	public static void main(String[] s)throws Exception
	{
		String str = &quot;I wanna print this!&quot;;
		byte[] b = str.getBytes();
		
		OutputStream os = System.out;
		os.write(b);
	}
}


</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/OSDemo.jpg" rel="attachment"><img class="size-full aligncenter" alt="Output Stream example" src="../../../images/OSDemo_400.jpg" /></a></p>
<hr/>
<h2>OutputStreamWriter + System.out</h2>
<pre class="brush: java; title: ; notranslate">
import java.io.*;
class OSWDemo
{
	public static void main(String[] s)throws Exception
	{
		String str = &quot;I wanna print this!&quot;;
		
		OutputStream os = System.out;
		OutputStreamWriter osw = new OutputStreamWriter(os);
		
		osw.write(&quot;Ankit Virparia\n\n&quot;);
		osw.flush();
		
		osw.write(str, 2,11);
		osw.flush();
		
		
	}
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/OSWDemo.jpg" rel="attachment"><img class="size-full aligncenter" alt="Output Stream Writer example" src="../../../images/OSWDemo_400.jpg" /></a></p>
<hr/>
<h2>BufferedWriter + OutputStreamWriter + System.out</h2>
<pre class="brush: java; title: ; notranslate">
import java.io.*;
class BufferedWriterDemo
{
	public static void main(String[] s)throws Exception
	{
		String str = &quot;I wanna print this!&quot;;
		
		OutputStream os = System.out;
		OutputStreamWriter osw = new OutputStreamWriter(os);
		BufferedWriter bw = new BufferedWriter(osw);
		
		bw.write(&quot;Ankit Virparia\n\n&quot;);
		bw.flush();
		
		bw.write(str, 2,11);
		bw.flush();		
	}
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/BufferedWriterDemo.jpg" rel="attachment"><img class="size-full aligncenter" alt="BufferedWriter example" src="../../../images/BufferedWriterDemo_400.jpg" /></a></p>
<hr/>
<h2>Console</h2>
<pre class="brush: java; title: ; notranslate">
import java.io.*;
class ConsoleWriteDemo
{
	public static void main(String[] s)
	{
		Console con = System.console();
		PrintWriter ps = con.writer();
		ps.print(&quot;Good Morning!&quot;);
		ps.println();
		
		con.writer().println(&quot;Hi&quot;); 
	}
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/ConsoleWriteDemo.jpg" rel="attachment"><img class="size-full aligncenter" alt="Console Write  example" src="../../../images/ConsoleWriteDemo_400.jpg" /></a></p>
<hr/>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/input-output/various-ways-to-write-on-console">Various ways to write on Console</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://ankit.co/tutorials/java-tutorials/input-output/various-ways-to-write-on-console/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Various ways to read from Console</title>
		<link>http://ankit.co/tutorials/java-tutorials/input-output/various-ways-to-read-from-console?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=various-ways-to-read-from-console</link>
		<comments>http://ankit.co/tutorials/java-tutorials/input-output/various-ways-to-read-from-console#comments</comments>
		<pubDate>Tue, 15 Jan 2013 10:33:16 +0000</pubDate>
		<dc:creator><![CDATA[Ankit Virparia]]></dc:creator>
				<category><![CDATA[Input Output]]></category>
		<category><![CDATA[Console]]></category>
		<category><![CDATA[IO]]></category>

		<guid isPermaLink="false">http://ankit.co/?p=522</guid>
		<description><![CDATA[<p>When we launch an application using java.exe using command prompt at that time, cmd.exe will be our parent application. So, in this tutorial we gonna learn various techniques to take some data from parent(command prompt) application. A stream object is available with us by default which is named as: System.in where by System is the [&#8230;]</p>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/input-output/various-ways-to-read-from-console">Various ways to read from Console</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></description>
				<content:encoded><![CDATA[<p>When we launch an application using java.exe using command prompt at that time, cmd.exe will be our parent application. So, in this tutorial we gonna learn various techniques to take some data from parent(command prompt) application. A stream object is available with us by default which is named as: <strong>System.in</strong> where by System is the class of java.lang package.</p>
<h2>InputStream &#8211; System.in</h2>
<pre class="brush: java; title: ; notranslate">
class ISDemo
{
	public static void main(String[] s)throws Exception
	{
		byte[] b = new byte[1024];
		System.out.print(&quot;Enter Text:&quot;);
		int cnt = System.in.read(b);	
		String userString = new String(b,0,cnt);
		System.out.println(&quot;No. of chars: &quot;+cnt);
		System.out.println(&quot;String: &quot;+userString);
	}	
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/ISDemo.jpg" rel="attachment"><img class="size-full aligncenter" alt="Input Stream Output" src="../../../images/ISDemo_400.jpg" /></a></p>
<hr/>
<h2>InputStreamReader + Systen.in</h2>
<pre class="brush: java; title: ; notranslate">
import java.io.*;
class ISRDemo
{
	public static void main(String[] s)throws Exception
	{
		InputStreamReader isr = new InputStreamReader(System.in);
		int data;
		String str = &quot;&quot;;
		char c ;
		while(true)
		{
			data = isr.read();
			c = (char)data;
			if(c=='\n')break;
			str += c;
		}
		
		System.out.println(&quot;String: &quot;+str);
	}	
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/ISRDemo.jpg" rel="attachment"><img class="size-full aligncenter" alt="Input Stream Reader Output" src="../../../images/ISRDemo_400.jpg" /></a></p>
<hr/>
<h2>BufferedReader +  InputStreamReader + Systen.in</h2>
<pre class="brush: java; title: ; notranslate">
import java.io.*;

class BufferedReaderDemo
{
	public static void main(String[] arg)throws Exception
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		System.out.print(&quot;Enter text:&quot;);
		String str = br.readLine();
		System.out.println(&quot;String: &quot;+str);	
	}
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/BufferedReaderDemo.jpg" rel="attachment"><img class="size-full aligncenter" alt="Buffered Reader Output" src="../../../images/BufferedReaderDemo_400.jpg" /></a></p>
<hr/>
<h2>Console</h2>
<pre class="brush: java; title: ; notranslate">
import java.io.*;
class ConsoleDemo
{
	public static void main(String[] s)
	{
		Console con = System.console();
		System.out.print(&quot;Enter String:&quot;);
		String str = con.readLine();
		System.out.println(&quot;String: &quot;+str); 
	}
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/ConsoleDemo.jpg" rel="attachment"><img class="size-full aligncenter" alt="Console Output" src="../../../images/ConsoleDemo_400.jpg" /></a></p>
<hr/>
<h2>Scanner</h2>
<pre class="brush: java; title: ; notranslate">
import java.util.*;

class ScannerDemo
{
	public static void main(String[] arg)
	{
		Scanner sc = new Scanner(System.in);
		System.out.print(&quot;Enter text:&quot;);
		String str = sc.nextLine();
		System.out.println(&quot;String: &quot;+str);	
	}
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/ScannerDemo.jpg" rel="attachment"><img class="size-full aligncenter" alt="Scanner output" src="../../../images/ScannerDemo_400.jpg" /></a></p>
<hr/>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/input-output/various-ways-to-read-from-console">Various ways to read from Console</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://ankit.co/tutorials/java-tutorials/input-output/various-ways-to-read-from-console/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Garbage Collector / Destructor in java</title>
		<link>http://ankit.co/tutorials/java-tutorials/garbage-collector/garbage-collector-destructor-in-java?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=garbage-collector-destructor-in-java</link>
		<comments>http://ankit.co/tutorials/java-tutorials/garbage-collector/garbage-collector-destructor-in-java#comments</comments>
		<pubDate>Mon, 14 Jan 2013 11:50:38 +0000</pubDate>
		<dc:creator><![CDATA[Ankit Virparia]]></dc:creator>
				<category><![CDATA[Garbage Collector]]></category>
		<category><![CDATA[Memory Management]]></category>

		<guid isPermaLink="false">http://ankit.co/?p=517</guid>
		<description><![CDATA[<p>Java is a object oriented programming language. As we all know that: It supports Objects, Methods, Variables, etc. When we create a new Object, It allocates space required for the class in HEAP memory of JAVA. Which can not be removed by any function call. That space is totally under control of JVM &#8211; Java [&#8230;]</p>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/garbage-collector/garbage-collector-destructor-in-java">Garbage Collector / Destructor in java</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></description>
				<content:encoded><![CDATA[<p>Java is a object oriented programming language. As we all know that: It supports Objects, Methods, Variables, etc. When we create a new Object, It allocates space required for the class in HEAP memory of JAVA. Which can not be removed by any function call. That space is totally under control of JVM &#8211; Java Virtual Machine. So, We can conclude that there is no concept like destructor in java. But for the memory management Java supports Garbage Collector mechanism.</p>
<h2>What is Garbage Collector?</h2>
<ul>
<li>It is a utility of Java Virtual Machine which is used to reclaim the space/memory allocated previously.</li>
<li>Compared to C++, in Java the developer need not to worry about freeing the memory.</li>
<li>Garbage Collection is done by a Thread named as: <strong>Garbage Collector</strong></li>
<li>Developer can not invoke Garbage collector. It is controlled by JVM. When JVM thinks that there is a need of removing memory, It starts the Garbage Collector Thread.</li>
<li>But we can of course send a request to JVM that: &#8220;Please invoke Garbage Collector!&#8221;. But it is just a request to JVM. It&#8217;s not a call. Garbage Collector may or may not be invoked. Commands to send such request are: 1) System.gc() 2) Runtime.gc().
</li>
<li>One most important part of Garbage Collector is: When garbage collector is invoked by JVM, finalize() method of our program will be invoked by JVM. So that developer can write/execute some code at that time.</li>
</ul>
<h2>Which objects will be removed by Garbage Collector?</h2>
<ul>
<li>Objects which are no where used further.</li>
<li>In case object has multiple referenced, All the references of that object are not used further.</li>
<li>Objects which are created inside a block and execution of that block is over</li>
<li>When parent object is not gonna used further, All the child objects are also unused.</li>
</ul>
<p>Above listed kind of objects will be removed by Garbage Collector.</p>
<h2>void finalize()</h2>
<p>As discussed above, a method named finalize() will be invoked when Garbage Collector is gonna remove the memory(object) of that class. So, that developer can write his end moment code. You can refer the below code to learn: <strong>How to write finalize() method.</strong></p>
<pre class="brush: java; title: ; notranslate">
import java.io.*;

class OpenAFile 
{
    FileInputStream aFile = null;
	String filename  = &quot;&quot;;
    OpenAFile(String filename) 
	{
		this.filename = filename;
        try 
		{
            aFile = new FileInputStream(filename);
        }catch (java.io.FileNotFoundException e) 
		{
            System.err.println(&quot;Could not open file &quot; + filename);
    	}
    }
	public  void finalize ()
	{
		try 
		{
            if (aFile != null) 
			{
				aFile.close();
				aFile = null;
			}
        }catch (Exception e) 
		{
            System.err.println(&quot;Could not close&quot; + filename);
    	}
		
	}
}
</pre>
<p><strong>Let me know in case you have any question.</strong></p>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/garbage-collector/garbage-collector-destructor-in-java">Garbage Collector / Destructor in java</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://ankit.co/tutorials/java-tutorials/garbage-collector/garbage-collector-destructor-in-java/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating directories using Java</title>
		<link>http://ankit.co/tutorials/java-tutorials/input-output/creating-directories-using-java?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=creating-directories-using-java</link>
		<comments>http://ankit.co/tutorials/java-tutorials/input-output/creating-directories-using-java#comments</comments>
		<pubDate>Mon, 14 Jan 2013 08:11:34 +0000</pubDate>
		<dc:creator><![CDATA[Ankit Virparia]]></dc:creator>
				<category><![CDATA[Input Output]]></category>
		<category><![CDATA[Directory]]></category>
		<category><![CDATA[File]]></category>
		<category><![CDATA[IO]]></category>

		<guid isPermaLink="false">http://ankit.co/?p=509</guid>
		<description><![CDATA[<p>Program to create a new Directory using File class: Output: Program to create multiple new Directories using File class: In case if we would like to create multiple nested directories, A different function is to be invoked. which is: mkdirs() Output:</p>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/input-output/creating-directories-using-java">Creating directories using Java</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></description>
				<content:encoded><![CDATA[<h3>Program to create a new Directory using File class:</h3>
<pre class="brush: java; title: ; notranslate">
import java.io.*;
class mkdirDemo
{
	public static void main(String[] s)
	{
		File f = new File(&quot;newDir&quot;);
		f.mkdir();
		System.out.println(&quot;Directory created.&quot;);	
	}	
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/newDirectory.jpg" rel="attachment"><img class="size-full aligncenter" alt="create 1 directory" src="../../../images/newDirectory_400.jpg" /></a></p>
</hr>
<h3>Program to create multiple new Directories using File class:</h3>
<p>In case if we would like to create multiple nested directories, A different function is to be invoked. which is: <strong>mkdirs()</strong></p>
<pre class="brush: java; title: ; notranslate">
import java.io.*;
class mkdirsDemo
{
	public static void main(String[] s)
	{
		File f = new File(&quot;a/b/newDir/testDir/c&quot;);
		f.mkdirs();
		System.out.println(&quot;Directories created.&quot;);	
	}	
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/mkdirsDemoOutput.jpg" rel="attachment"><img class="size-full aligncenter" alt="create multiple directories" src="../../../images/mkdirsDemoOutput_400.jpg" /></a><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/mkdirsDemo.jpg" rel="attachment"><img class="size-full aligncenter" alt="create multiple directories" src="../../../images/mkdirsDemo_400.jpg" /></a></p>
</hr>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/input-output/creating-directories-using-java">Creating directories using Java</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://ankit.co/tutorials/java-tutorials/input-output/creating-directories-using-java/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
