<?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; Input Output</title>
	<atom:link href="http://ankit.co/category/tutorials/java-tutorials/input-output/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>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>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>
		<item>
		<title>Listing content of given Directory</title>
		<link>http://ankit.co/tutorials/java-tutorials/input-output/listing-content-of-given-directory?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=listing-content-of-given-directory</link>
		<comments>http://ankit.co/tutorials/java-tutorials/input-output/listing-content-of-given-directory#comments</comments>
		<pubDate>Mon, 14 Jan 2013 07:27:45 +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=506</guid>
		<description><![CDATA[<p>Our goal is to read the content of given directory and list all the files and folders available inside it. To retrieve list of files/folders inside the given folder, we can call list() method of File class as shown in the example. Output:</p>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/input-output/listing-content-of-given-directory">Listing content of given Directory</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></description>
				<content:encoded><![CDATA[<p>Our goal is to read the content of given directory and list all the files and folders available inside it. To retrieve list of files/folders inside the given folder, we can call list() method of File class as shown in the example.</p>
<pre class="brush: java; title: ; notranslate">
import java.io.*;
import java.util.*;
class ListDirContent 
{
	public static void main(String args[]) 
	{
		String dirname = &quot;&quot;;
		System.out.print(&quot;Enter a path:&quot;);
		Scanner sc = new Scanner(System.in);
		dirname = sc.nextLine();
		
		File f1 = new File(dirname);
		if (f1.isDirectory()) 
		{
			System.out.println(&quot;Directory of &quot; + dirname);
			String s[] = f1.list();
			for (int i=0; i &lt; s.length; i++) 
			{
				File f = new File(dirname + &quot;/&quot; + s[i]);
				if (f.isDirectory()) 
				{
					System.out.println(s[i] + &quot; is a directory&quot;);
				} 
				else 
				{
					System.out.println(s[i] + &quot; is a file&quot;);
				}
			}
		} 
		else 
		{
			System.out.println(dirname + &quot; is not a directory&quot;);
		}
	}
}
</pre>
<p><strong>Output:</strong><br />
<a class="highslide"  onclick="return hs.expand(this)" href="../../../images/ListDirContent.jpg" rel="attachment"><img class="size-full aligncenter" alt="List directory content" src="../../../images/ListDirContent_400.jpg" /></a></p>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/input-output/listing-content-of-given-directory">Listing content of given Directory</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/listing-content-of-given-directory/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introduction to Stream</title>
		<link>http://ankit.co/tutorials/java-tutorials/input-output/introduction-to-stream?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=introduction-to-stream</link>
		<comments>http://ankit.co/tutorials/java-tutorials/input-output/introduction-to-stream#comments</comments>
		<pubDate>Sun, 13 Jan 2013 18:18:01 +0000</pubDate>
		<dc:creator><![CDATA[Sonali Virparia]]></dc:creator>
				<category><![CDATA[Input Output]]></category>

		<guid isPermaLink="false">http://ankit.co/?p=500</guid>
		<description><![CDATA[<p>What is a stream? Before we come to the actual definition of stream let us first consider an example in terms of operating system. We can have multiple applications running on our system. In order to identify each application an OS makes use of port numbers. When we send some data from one port to [&#8230;]</p>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/input-output/introduction-to-stream">Introduction to Stream</a> appeared first on <a rel="nofollow" href="http://ankit.co">Ankit Virparia</a>.</p>
]]></description>
				<content:encoded><![CDATA[<h3>What is a stream?</h3>
<p>Before we come to the actual definition of stream let us first consider an example in terms of operating system. We can have multiple applications running on our system. In order to identify each application an OS makes use of port numbers. When we send some data from one port to another then we are forming a stream between the two. So stream here is the direction or we can also say a combination of source port and destination port.</p>
<p>Consider an example: suppose we want to execute a java application. To do that we first start command prompt. So the OS assigns some port number P1 to it. Now to compile our java application we use javac.exe which is the compiler for java and OS assigns port number say P2 to it. But compiling is a small process so it will finish early. Once the application is compiled we launch our application using java interpreter i.e. java.exe. OS assigns it a port number say P3. According to the feature of JRE, it creates two static objects: in and out, identifying the direction from P1 to P3 and from P3 to P1 respectively. Both these objects have been declared in java.lang.System class. </p>
<p>Therefore whenever we want to take some input into our application we have to specify the direction using <strong>System.in</strong> and when we want to send some output from our application we have to specify its direction using <strong>System.out</strong>. There are mainly two streams in java: <strong>byte stream</strong> and <strong>character stream</strong>. Detailed discussion on both the streams would be done in next tutorial. </p>
<p>The post <a rel="nofollow" href="http://ankit.co/tutorials/java-tutorials/input-output/introduction-to-stream">Introduction to Stream</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/introduction-to-stream/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
