Sunday, June 3, 2012

File Handeling and I/O Using JAVA

Welcome all of you to my very first post in this blog... :) :)


I thought of writing a blog very long ago.. but didn't have enough time to complete it with my university work. Finally i decided to publish some posts which i have completed....:) :)

Today I would like to share with you, something regarding file handling using JAVA. In this post I have assumed that  you have the basic knowledge in object orientation. Even you don't have that you can still follow this post, but it will be little hard to understand in a theocratic manner, but I think having some experience will help u to understand object orientation well when u learn it :)    I hope to write a post on object orientation also in near future :)

JAVA has a package called io for handling files. It can be used for many purposes like creating files,directories,writing into files, deleting files, object serialization etc. I will not discuss serialization in this post, but very soon in the future. You can view the contain of this package through the JAVA api   http://docs.oracle.com/javase/6/docs/api/  Even there are different IDE tools available, in this post I will code in notepad since, we are not fortunate enough to have IDE's at our exams :D :D

First i think i must mention how to configure java for an absolute beginner....:)

In this post i have explained how it can be done.....:)

http://fewdropsfromjava.blogspot.com/2012/06/configuring-java-for-absolute-beginners.html



ok let's begin.......

first we must import JAVA io package contents into our java file.

import java.io.*;

from the * sign we tell that all the contents in the io package should be included.

Creating a new file



The above is the code for creating a new file. IO operations can cause Exceptions. If u don't know what an exception is, it is some sort of a error which occurs under certain conditions(NOT always).
In java exceptions should be handled correctly, in order to make sure ur program won't crash in the middle of execution.

Exception Handling is a detailed section but in brief we can say there are two ways of handling exceptions. One is using throws key word. Using throws keyword we notify the compiler that we know this method can throw exceptions, but ignore that danger of getting an exception in the run time and compile the program(this is used in the above code). This procedure is also used when there is a hierarchy of classes, and we handle an exception thrown by a method inside a particular class, by a subclass class in that hierarchy.

The other way is using try and catch blocks, in this approach we keep the statements which can throw an exception inside the try block, and inside the catch block we state what  the program should do if such exception is occurred.

here is an example



In the parentheses of the catch block we mention the type of Exception, for which the catch block will execute, in this example by mentioning IOException i have told that if the try block throws an IOException (this means exception thrown by IO(input output) operations), execute the code in the catch block.

Ok,.. I hope you have got a basic idea about exception handling...:)

Let's now see what i have done in the code.

File file1=new File("firstfile.txt");

by this line i have created a new Object of the File class and assigned it to “File” type  variable "file1". I have used the constructor which accepts a string parameter in the File class and passed the name and the file format of the file that I want to create, into it. If you specify only the name and the file format that file will be created in the same directory where you will save your java file. Otherwise you can give a different directory like this,

File file1=new File("E:/Documents/Namila/Java/blog/IO/Namila/firstfile.txt");

something to note here is normally windows explorer use "\" character to specify addresses. But in java u have to use "/" or u can also use "\\".

When we create a new file object as above, only the name of the file is created, but NOT the actual file. In order to create the actual file you have to call the createNewFile()  method in that File object   
file1.createNewFile();

Ok now let's save our program now.
Some points to note in saving are

  • We must use ".java " format for saving. ex  A.java
  • If there is a class in our program which has used the public access modifier, we MUST save our program with that file name.
  • Otherwise we can save our program in any name, but we must use the same name for compiling.
  • And when running our program, we have to run it by the class name which contains the main method
  • So it's more convenient to save the file with the name of the class which has the main method, since we can use the same name for both compiling and running...:)




Running the Program
Go to the directory where u have saved the java file using the command prompt, and type

javac A.java 

"javac" command is used to invoke the java compiler to compile our code. This will check our code for any syntax errors and turn it into something called "Bytecode" and save as a class file which is an intermediate state between the machine language and the human understandable java codes. Then type

java A

"java" command is used to invoke the java virtual machine which executes our code. These explanations are really not necessary for the today's topic, but i just mentioned them for you to be kept know......:) :) 


And if we go and check the directory which we have saved the java file, we can see that "firstfile.txt" has been created!!




 
       It is not only "txt", u can use any file format like html, xml....etc.

That's all for this post.....:)



I hope to discuss this topic future in the next post.... I hope u have understood this post even though i am not very good at     "Explaining Something "  :D :D

So  try out this by yourself and please let me know if u have any problems. I would be glad to answer them as much as i can....:)

And one more thing.............Since I am not an expert blogger there can be some inconveniences faced by you while reading this.........I apology for those and please comment with any of them and ur ideas....

It will be very valuable to improve my future blogs............:)

Bye for now.......... TC.....:) :)

8 comments:

  1. If this is introduction to Java, it is good to start with Hello World Prog.
    Also If u talk about file handling, then no need to mention the details of Error Handling (which confuses the reader).
    If u want, do that in a different post

    In ur blog it says :
    ...ignore that danger and compile the program ...
    It is not the compile time error, caught by the throw. It is Run Time errors

    Also ur explanation about try-catch / throw part doesn't seem to be correct

    Little corrections :

    ...by this line i have created a new Object of the File class and assigned it to variable
    Of the variable type "File", named "file1".
    [Note that the variable type is something like int(not exactly though), String and so on

    Inside the constructor i have ...
    It is not that u write inside the constructor!
    The constructor is Java's, not urs.
    U r using the constructor of File class which accepts a String parameter

    ReplyDelete
  2. Correct your mistakes and keep up the good work...

    ReplyDelete
  3. We aim to provide our applicants with outstanding care and we take your comments to spirit.As always, we enjoy your confidence and trust in us
    Selenium Training in Chennai

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete