Sunday, September 30, 2007

File Handling: Using FileOutputStream

If you want to write to a file we use the FileOutputStream class. FileOutputStream is meant for writing streams of raw bytes such as image data. (from JAVA API)

The following are constructors of this class from JAVA API:

FileOutputStream(File file)
Creates a file output stream to write to the file represented by the specified File object.
FileOutputStream(File file, boolean append)
Creates a file output stream to write to the file represented by the specified File object.
FileOutputStream(FileDescriptor fdObj)
Creates an output file stream to write to the specified file descriptor, which represents an existing connection to an actual file in the file system.
FileOutputStream(String name)
Creates an output file stream to write to the file with the specified name.
FileOutputStream(String name, boolean append)
Creates an output file stream to write to the file with the specified name.

SAMPLE CODE:

Let's use the code from the sample code of FileInputStream:

/**
* @(#)ReadFile.java
*
* @JEDI Phase II Course Material
* @With comments insertions from
* @ erlyn manguilimotan
*/

import java.io.*;

public class ReadFile {

public static void main(String args[]){

BufferedReader fileRead = new BufferedReader (new InputStreamReader(System.in));
String fileName = "";
System.out.println("Enter the name of the file to Open");
try{
fileName=fileRead.readLine(); //input the name of the file
}catch(IOException e1){
}//end of catch

FileInputStream rf = null; //create an object for FileInputStream

try{
rf = new FileInputStream(fileName); //connects the object with the file name
}catch(FileNotFoundException e2){
System.out.println("File not found...");
}//end of catch

try{
char data; //variable to hold the data
int temp=0;
do{
temp=rf.read(); // Reads a byte of data from this input stream.
data = (char) temp; //stores the data into variable data
if(temp!=-1) //while it's not the end of file
{
System.out.print(data);
}
}while(temp!=-1); //ends the loop if it's the end of file.

}catch(IOException e3){
System.out.println("Problem in reading the file..");

}//end of catch

//WE WILL INSERT THE CODE HERE

} //end of main
}//end of class

Now let us insert the following code as indicated above:
*************************************************************
System.out.println("---------------------------------------");
System.out.println("Now let's try to add a line in the file");
System.out.println("We will use the same file");

FileOutputStream fos = null; //creates object for FileOutputStream
try{
fos = new FileOutputStream(fileName); //connects the object to the file
}catch(FileNotFoundException e4){ //exceptions
System.out.println("File cannot be opened for writing");
}

try{
boolean done = false; //used to text the loop
int data;
do{//do while the line is not a '.'
data=fileRead.read();// read from keyboard
if((char) data =='.')
done=true;
else
fos.write(data); //write to file
}while(!done);
}catch(IOException e5){
System.out.println("Problem in reading from file");
}

*************************************************************

Compile and execute the program. Check on syntax errors.

Note: Make sure you still have the text file you had earlier.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
QUESTION:

What happened to your text file? Check the content of your text file again.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

File Handling: Reading from a File

To read input data, by default we use the computer keyboard. However, some of the data we need maybe stored in some data file. For example, if you have a class record stored in a file and you want to retrieve it, or simply want to read a text file using your java program.


Reading from a file:

The FileInputStream class allows you to read data from a file.

The class has the following constructors:

o FileInputStream(File file)
Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system.

o FileInputStream(FileDescriptor fdObj)
Creates a FileInputStream by using the file descriptor fdObj, which represents an existing connection to an actual file in the file system.

o FileInputStream(String name)
Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system.

(Descriptions taken from http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileInputStream.html)


Let’s try the FileInputStream class.


First, create a text file and save it in the same directory where you create the class.


Second, try this code:

/**
* @(#)ReadFile.java
*
* @JEDI Phase II Course Material
* @With comments insertions from
* @ erlyn manguilimotan
*/

import java.io.*;

public class ReadFile {

public static void main(String args[]){

BufferedReader fileRead = new BufferedReader (new InputStreamReader(System.in));
String fileName = "";
System.out.println("Enter the name of the file to Open");
try{
fileName=fileRead.readLine(); //input the name of the file
}catch(IOException e1){
}//end of catch

FileInputStream rf = null; //create an object for FileInputStream

try{
rf = new FileInputStream(fileName); //connects the object with the file name
}catch(FileNotFoundException e2){
System.out.println("File not found...");
}//end of catch

try{
char data; //variable to hold the data
int temp=0;
do{
temp=rf.read(); // Reads a byte of data from this input stream.
data = (char) temp; //stores the data into variable data
if(temp!=-1) //while it's not the end of file
{
System.out.print(data);
}
}while(temp!=-1); //ends the loop if it's the end of file.

}catch(IOException e3){
System.out.println("Problem in reading the file..");
}//end of catch
} //end of main
}//end of class

Compile and execute the code.

NOTE! Make sure you have a text file to open! You may want to use the following contents for your text file:

Hello World!
This is a sample file to be read by a java file.
How does the output appear on your screen?

*******************************************************************************

Thursday, September 27, 2007

Java Education and Development Initiative (JEDI)

JEDI is a project of Sun Microsystems, Inc through the Java Research and Development Center of the University of the Philippines. Its partnership with the Philippine Society of IT Educators (PSITE) was launched way back in February 2005 during the PSITE National Conference in Cagayan de Oro City. I was there during its launching.

Ateneo de Zamboanga University is one of the JEDI School members. As a member school, we have access to JEDI course materials, faculty training, online community, software and other development tools to mention some benefits.

Teachers of our department have joined the JEDI Phase I and II Training. In Phase II, I was one of the participants of the Software Engineering Course held in Dipolog City last May 2007.

I am using the JEDI course materials for my classes. I share this with my students so I need spend much time to prepare for my classes. Just review and practice some codes then I am ready for my class!

JEDI is such a help to the academic community. For more information, please visit http://jedi.upcompsci.net/


Be a JEDI SCHOOL!!! Join now!

Adding Java Listeners

In my class, we are now doing GUI using Abstract Window Toolkit (AWT). In one of our lab exercises, we mimicked a messenger window where the user types in the message and by pressing the "enter" key or by clicking the SEND button, the message is transfered to the display area.

To add listeners, for the buttons SEND and QUIT I used the ActionListeners and for the "ENTER"key, I used the KeyListener and added it to the TextArea object msg.


Here's the resulting window for the given code:

/**
* @(#)MyMessenger.java
*
*
* @Erlyn Q. Manguilimotan
* Computer Science Department

* Ateneo de Zamboanga University
* @version 1.00 2007/9/26
*/

import java.awt.*;
import java.awt.event.*;

public class MyMessenger extends Frame implements ActionListener, KeyListener{

private TextArea disp; // object for the display area
private TextArea msg;
// object for the message area

public MyMessenger(){

Panel dispPanel = new Panel();
//panel where the TextArea object disp is to be placed

Panel msgPanel = new Panel();
//panel where the TextArea object msg is to be placed

Panel buttonsPanel = new Panel();
//panel where the buttons send and quit
are to be placed
Button send = new Button("SEND");//button for SEND
Button quit = new Button("QUIT");//button for QUIT

disp = new TextArea("",8,30,TextArea.SCROLLBARS_VERTICAL_ONLY);
//textarea for disp with 8 rows and 30 columns

msg = new TextArea("",8,30,TextArea.SCROLLBARS_VERTICAL_ONLY);
//textarea for disp with 8 rows and 30 columns

disp.setBackground(Color.PINK); //set background of display area to pink
disp.set
Editable(false); //set the display area to not editable mode

setSize(300,350); //set framesize
setLayout(new BorderLayout());//set Frame layout
setBackground(Color.lightGray); //set frame background color
setTitle("My Messenger"); //set Frame title

add(dispPanel,BorderLayout.NORTH); //add panels to the frame
add(msgPanel
,BorderLayout.CENTER);
add(buttonsPanel,BorderLayout.SOUTH);

dispPanel.add(disp); //add d
isp TextArea to dispPanel
msgPanel.add(msg);//add msg TextArea to msgpPanel
msg.addKeyListener(this);//add key listener to msg TextArea
buttonsPanel.add(send); //add buttons to panel
buttonsPanel.add(quit);
send.addActionListener(this); // add ActionListener to button when clicked
quit.addActionListener(this);

addWindowListener(new FrameListener()); //adding window Listener
setResizable(false);
setVisible(true);

}

public static void main(String args[])
{
MyMessenger ym = new MyMessenger(); // instantiating MyMessenger Class
}


public void actionPerformed (ActionEvent e)
{
if(e.getActionComm
and()=="SEND") //if SEND button is clicked
{ String temp=""; //temp string
temp=msg.getText(); //recieves the text from msg TextArea
disp.append(temp); //transfers by append method to display area
msg.setText(""); //sets message area to empty again
}
else
System.exit(0);

}

public void keyPressed (KeyEvent e){


if(e.getKeyCode()== e.VK_ENTER) //if Enter key is pressed
{ String temp=""; //temp string
temp=msg.getText(); //recieves the text from msg TextArea
disp.append(temp); //transfers by append method to display area
msg.setText(""); //sets message area to empty again
}

}


public void keyReleased(KeyEvent e){
}

public void keyTyped (KeyEvent e){
}

}



To close the window, I used a class called FrameListener.java which extends WindowAdapter. Here's the code:

import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;

class FrameListener extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}

You may try this code. This still needs some improvement or polishing. You may suggest some codes on how to improve the GUI.

Thank you...

Wednesday, September 26, 2007

Introduction

Hey guys!

Let's learn Java Programming Language!

I welcome everyone to my blog. This blog is dedicated for java codes, java projects, java problems, anything about Java Programming Language.

I'm teaching Java for the first time. I thought it is VERRRYY difficult, but no! Object-oriented programming is one great concept and Java just have it all.

Let's learn the Java language together! Join me as I enter tutorial notes, experiences with Java programming and some codes I started tinkering for my classes.

Thanks for dropping by!