Sample Java Programs

Hello World

/* This is my first program, it is designed to
demonstrate a simple program structure 
Author: Ramneet Singh
*/

import java.io.*;

class MyFirst
{	
	public static void main(String[ ] args)
	{	
		System.out.println (" Dear Friends, Sat Shri Akal!!");
	}
}

IF

import java.io.*;

class payCheck
{	
	public static void main(String[ ] args)
	{
		double mySalary, myBaseSalary, myOverTime, hourlyRate;
		int hours;

		myBaseSalary = 10000;         
		hourlyRate = 5.50;
		hours = 10;

		// well use a control structure to check for overtime payments
		if ( hours > 0 ) 
			{
				myOverTime = hourlyRate * hours;
				mySalary = myBaseSalary + myOverTime;
			} // end if
		else     
			{
				mySalary = myBaseSalary;
			} // end else

		// Now print out the result
		System.out.println (" Your salary this week is: " +  mySalary);
	} // end method definition

} // Leave a space behind end class bracket so we can easily tell it apart

WHILE..

import java.io.*;

class MyFinance
{	
	public static void main(String[ ] args)
	{
		// declare storage for variables
		double mySalary, myExpenses, myOverdraft, mySaving, surplus;
		int years;
		// initialise variables
		mySalary = 10000;         
		myExpenses = 9500;
		myOverdraft = 20000;
		mySaving = 0;
                    	years = 0;
	
		//calculate a value for surplus
		surplus = mySalary - myExpenses;

		// test for the condition then execute block
		while ( mySaving < myOverdraft )
			{ 
				mySaving = mySaving + surplus;
				years++;
                                   }			

			// print out the result
		System.out.println (" It is going to take you " + years + 								"years to pay off your overdraft! ");
	}

}

FOR..

import java.io.*;

class flatBroke
{	
	public static void main(String[ ] args)
	{
		for ( int i =10; i>0; i-- )
                                   {
				System.out.println( "Pounds left: œ" + i );
			} // end actions depending on counter			 
		System.out.println( " Flat Broke!" );			
	} // end method

} // end class definition

SWITCH...

import java.io.*;

class MyFinance
{	
	public static void main(String[ ] args)
	{
		double mySalary, myExpenses, myOverdraft, mySaving, surplus;
		int years;

		mySalary = 10000;         
		myExpenses = 9500;
		myOverdraft = 20000;
		mySaving = 0;
                    	years = 0;
	
		//calculate a value for surplus
		surplus = mySalary - myExpenses;
                                    
                       // cast mySalary to int for switch statement
                       int payCheck = (int)mySalary;

		//check salary and issue cautionary warning!
		switch ( payCheck )
			{
				case 10000:
				System.out.println (" One day you will earn more 								money!"); 
				break;
				
				case 15000:
				System.out.println (" 15000 is not a bad salary..."); 
				break;

				case 20000:
				System.out.println (" You shouldn't really have an 								overdraft!"); 
				break;

				default:
				// no default behaviour needed, we only need 3 						// messages
				break;
			} // end switch statement
				
			//test for the condition then execute block
		while ( mySaving < myOverdraft )
			{
				mySaving = mySaving + surplus;
				years++;
                                   } // end while

		// print out the result
		System.out.println (" It is going to take you " + years + 								"years to pay off your overdraft! ");
	} // end method
		
} // end clss definition

METHODS...

import java.io.*;

class methods
{
     	public static void main( String[ ] args )
           	{
            	int number=4;      // initialises the number to 4      
            	int answer=Square(number);   // calls the method square to 									// deliver a value							Display(answer);    // Displays the value found in answer
           	} 

    	
	public static int Square( int x)    // Takes an integer x as an argument
           	{
            	return x*x;   // returns the result as an integer
           	}

    	
	public static void Display( int a)  // Takes an integer and displays it
           	{
            	System.out.println(" The answer is: " + a);   
           	}
 
}

CLASSES..

import java.awt.*;
import java.awt.image.*;
	
abstract class Aeroplane extends Object  
// create an aeroplane template - an  abstract class would never be 			
//instantiated, only used to derive specialised classes from.
{
	// give it some necessary data
	public int speed;                           		
	public int height;
	public int engines;
	public int fuel;
		
	// tell it where it is on the screen
	int x, y;                                          
		
	//construct an object
	Aeroplane( )                                  		
	{
		this.x = 100;
		this.y = 100;
	}

	public abstract void Draw( Graphics g, ImageObserver o );

	public void Fly( )
	{
		.......// as if by magic!
	}

} // end class definition 	


class Airliner extends Aeroplane
{
	public Airliner( )
	{
		super( );
		private int seats;                 
	}

	public void Draw( Graphics g, ImageObserver o );
           {
	 	// Graphics code goes here
	}

}   // ends class definition

	
class Fighter extends Aeroplane
{
	public Fighter( )
	{
		super( );
		private int guns;
	}
		
	public void Draw( Graphics g, ImageObserver o );
	{
		// Graphics code goes here
	}

} // ends class definition

MORE CLASSES

// This is the main class, which declares an instance of address, defined below

import java.io.* ;

public class Contact
{
   	public static void main( String[] args)
   	{
    		String name = "Joe Soap";

		// create new object
    		address a = new address( "10 Downing Street", 
			      		"Westminster","London","England");   				System.out.println("Name= " + name +"Address= "+
						 			a.retrieve( ));
    	}

}

class address
   {
      	private String street;
      	private String city;
      	private String county;
      	private String country;
      		
	// established data storage, now construct class
	// passing it some values as parameters

      	public address( String s, String c, String co, String cou )
      	{
         		street = s;
         		city = c;
         		county = co;
         		country = cou;
     	}
		
	    		
	//provide an accessor method to pass data with
	public String retrieve( )
      	{
         		return street + "," + city + "," + county +"," + country;
      	}
 
} // end class definition

GUIs (JDK 1.0)

import java.awt.*;

public class Bets extends Frame
{
   	Choice numbers;   // gives us a pull down menu to list the numbers
   	TextField bet;        // holds the actual bet
   
   	public Bets( )                      //construct the object
  	{ 
      		numbers = new Choice( );      // initialise the pull down menu
      		numbers.addItem("1");
      		numbers.addItem("2");
      		numbers.addItem("3");
      		numbers.addItem("4");
      		numbers.addItem("5");
      
      		bet = new TextField(2);        // initialise a Text Field to hold 2 digits
      
      		Panel p = new Panel( );         // initialise a panel to put things on 
      		p.setLayout(new FlowLayout( ));   // get a layout manager
      		p.add(new Button("GO"));      // add a button to the panel
      		p.add(new Label("Stake"));
      		p.add(numbers);
      		p.add(new Label("Bet"));
      		p.add(bet);
      		add("South", p);   // add the panel and all its components at 							// base
      	}
   
             // we need a method to look after our choices 

   	public boolean action(Event e, Object o)   
   	{
    		String result= null;
   		if (e.target.equals(numbers))
        		{
           		 	result = Integer.toString(numbers.getSelectedIndex( )+1 );
            		bet.setText( result);
        		}
    		else if (o.equals("GO"))
         		{
			start( );
		}
         		return true;
   	}
   
   
   	public void start( )
   	{
      			//Insert code here to start race
   	}
  
           // what happens if we close the window?
	public boolean handleEvent(Event e)
   	{
    		if (e.id == Event.WINDOW_DESTROY)
       		System.exit(0);
     		else return super.handleEvent(e);
     		return true;
  	}
   
   	public static void main(String[] args)
   	{
      		Frame f = new bets( );   //declare and initialise a Frame
      		f.resize(300, 100);           // how big is it?
      		f.show( );                        // wheel it on screen!
   	}
	
} // end class definition

SUPERCALCULATOR (JDK 1.0)

import java.awt.*;

public class Calculator extends Frame
{
   	Display out;
   	Keypad in;
   	Maths sums;

   	public Calculator( )
   	{
      		setLayout(new BorderLayout( ));
   
      		out = new Display( );
      		in = new Keypad(out);
      		sums = new Maths(out);
   
      		add("North", out);
      		add("Center", in);
      		add("East", sums);
   	}
   
   	public boolean handleEvent(Event e)
   	{
    		if (e.id == Event.WINDOW_DESTROY)
       		System.exit(0);
     		else return super.handleEvent(e);
     		return true;
  	}
   
   	public static void main(String[] args)
   	{
      		Frame f = new calculator( );
      		f.resize(100, 200);
      		f.show( );
   	} 
   
}


class Display extends Panel
{
   	TextField show;
   
   	public Display( )
      	{
         		show = new TextField(10);
         		Panel p = new Panel( );
         		p.add(show);
         		add ("Center", p); 
     	}
       
   	public void write( String s)
      	{
         		show.setText(s);
      	}
      
   	public String read()
      	{
         		return show.getText();
      	}
   
}


class Keypad extends Panel
{   
      	Display monitor;
      
      	public Keypad(Display mymonitor)
      	{                       
         		monitor = mymonitor;
         		Panel p = new Panel();
         		p.setLayout( new GridLayout(5,3));
      
         		for ( int i = 0; i <= 9; i++)
          			{
				p.add(new Button("" + (char)('0' + i)));
			} 
          		p.add(new Button("."));
          		p.add(new Button(""));
          		p.add(new Button(""));
          		p.add(new Button(""));
          		p.add(new Button("C"));
        
      		add("Center", p);
       	}
       
       	public boolean action(Event e , Object o)
       	{        
               	char c = ((Button) e.target).getLabel().charAt(0);  
               	switch(c)
               	{
                     		case '0':
                     		case '1':
                    	 	case '2':
                     		case '3':
                     		case '4':
                     		case '5':
                     		case '6':
                     		case '7':
                     		case '8':
                     		case '9':
                     		case '.':
                     		monitor.write(monitor.read( ) + c);
                     		break;
                     
                     		case 'C':
                     		monitor.write("");
                    	 	break;
                	}
               	return true;
       	}         
       
}


class Maths extends Panel
{  
   	Display monitor; 
   	double num1, num2, result;
   	char operand;
        
   	public Maths(Display mymonitor )
   	{  
      		monitor = mymonitor;   
      		Panel p = new Panel();
         		p.setLayout( new GridLayout(5,1));
         		p.add(new Button("+"));
         		p.add(new Button("-"));
         		p.add(new Button("*"));
         		p.add(new Button("/"));
         		p.add(new Button("="));
         
         		add("North",p);
   	}
   
   	public boolean action(Event e , Object o)
       	{      
             	char c = ((Button) e.target).getLabel().charAt(0); 
              	switch (c)
              	{
                		case '+':
                		case '*':
                		case '-':
                		case '/':
                		num1 = Double.valueOf(monitor.read( )).doubleValue( );       
                		operand = c;
                
                		monitor.write("");
                		break;
                
                		case '=':  
                		num2 = Double.valueOf(monitor.read( )).doubleValue( );
                		result = sum(num1, num2, operand);                
                		monitor.write(String.valueOf(result));
              	}
      
         	return true;    
       	}
       
       
    	public double sum( double x, double y, char z )
    	{
      		double answer = 0;
      		if ( z == '+') answer = x + y;
      		else if ( z == '-') answer = x - y;
      		else if ( z == '*') answer = x * y;
      		else if ( z == '/') answer = x / y;
      		return answer;
    	}

}

EVENT HANDLING IN JDK1.1 - #1 BUTTON

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
	
//We are going to implement the ActionListener interface
public class myNewButton extends Applet implements ActionListener
{
   	Button b;
   	TextField t;
   	int num, result;
   		
	public void init( )
   	{
      		b = new Button("Double");

		// now associate the ActionListener with the button
      		b.addActionListener(this);

      		t = new TextField(7);
      		t.setText("100");
      
      		add(b);
      		add(t);
   	}
  
  	// ActionListener has only one method - actionPerformed, which we must 				
	// implement
  	public void actionPerformed( ActionEvent e)
   	{
            	num = Integer.parseInt(t.getText());
            	result = num * 2;
            	t.setText( Integer.toString(result));
   	}

}

EVENT HANDLING IN JDK1.1 - #2 MULTIPLE BUTTONS

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

public class myNewTwoButtons extends Applet implements ActionListener
{
   	Button b, b1;
   	TextField t;
   	int num, result;
   		
	public void init( )
   	{
      		b = new Button("Double");
      		b.addActionListener(this);
		// set tag for Action Listener to recognise button b by.
		b.setActionCommand("2");
      		b1 = new Button("Treble");
		// the code doesnt require a tag, but it works both ways!
      		b1.addActionListener(this);
      		t = new TextField(7);
      		t.setText("100");
      
      		add(b);
      		add(t);
      		add(b1);
   	}
  
  
  	public void actionPerformed( ActionEvent e)
   	{
            	num = Integer.parseInt(t.getText( ));
            	String s = e.getActionCommand( );
            	if (s == ("2"))
               	{
                  		result = num * 2;
               	}
            	else if (s == ("Treble")
		{
			result = num * 3;
		}
            	t.setText( Integer.toString(result));
   	}

}

EVENT HANDLING IN JDK1.1 - #3 USING LOCAL CLASSES

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

public class myLocalButton extends Applet 
{
   	private ActionListener al;
   	private Button b;
   	private TextField t;
   	private int num, result;
   
	public void init( )
   	{
      		b = new Button("Double");
      		al = new buttonListener( );
      		b.addActionListener(al); 
      		t = new TextField(7);
      		t.setText("100");
      
      		add(b);
      		add(t);
   	}
  
 	class buttonListener implements ActionListener
 	{ 
  		public void actionPerformed( ActionEvent e)
   		{
            		num = Integer.parseInt(t.getText());
            		result = num * 2;
            		t.setText( Integer.toString(result));
   		}
 	}  
 
}

EVENT HANDLING IN JDK1.1 - #4 ANONYMOUS INNER CLASSES

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

public class myNewInnerButton extends Applet 
{
   	Button b;
   	TextField t;
  	int num, result;
   	
	public void init( )
   	{
      		b = new Button("Double");
		/* declare and define anonymous inner class, notice the opening 
                                 bracket before new, is not closed until the end of the class definition.*/      				b.addActionListener(new ActionListener( ){
            		public void actionPerformed(ActionEvent e)
               		{
                  			num = Integer.parseInt(t.getText( ));
                  			result = num * 2;
                  			t.setText( Integer.toString(result));  
               		}
		// close both sets of brackets here, class and method call
         		});
     		
		t = new TextField(7);
      		t.setText("100");
      
      		add(b);
      		add(t);
   	}
  
}

EVENT HANDLING IN JDK1.1 - #5 CLOSING WINDOWS

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


public class myWindowEvent extends Frame 
{
   	private Button b;
            // constructor for class  
   	public myWindowEvent( )
   	{         
		// create button and attach ActionListener 
      		b = new Button("Quit");
      		b.addActionListener(new ActionListener( ){
         			public void actionPerformed( ActionEvent e )
         			{
            			close( );
         			}
      		});
			
		// we still need to handle the Window Event, but we dont want to 				//implement all seven methods, so we use WindowAdapter      
      		this.addWindowListener(new WindowAdapter( ){
         			public void windowClosing(WindowEvent e)
         			{
            			close( );
         			}
      		});
      
      
      		add(b);
            }
   		
	// method used by both listeners!
   	public void close( )
   	{
      		System.exit(0);
   	}
   
   
   	public static void main(String[] args)
   	{
      		Frame f = new myWindowEvent( );
		// resize is a deprecated method under 1.1, so we use pack( ) instead
      		f.pack( );
      		f.show( );      
   	}
 
}

EVENT HANDLING IN JDK1.1 - #6 MENUS

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

public class myMenuEvent extends Frame 
{
   	private Button b;
   	private MenuItem wheat, bacon, eggs, toast;
   	private CheckboxMenuItem hot, iced;

   	public myMenuEvent( )
   	{
      		setLayout(new BorderLayout(20,20));
      			
		// Add button and look after window closing
      		b = new Button("Quit");
      		b.addActionListener(new ActionListener( ){
         			public void actionPerformed( ActionEvent e )
         			{
            			System.exit(0);
         			}
      		});
      
      		this.addWindowListener(new WindowAdapter( ){
         			public void windowClosing(WindowEvent e)
         			{
                			System.exit(0);
         			}
      		});
      			
			// for clarity set up menu first then listeners!
      		MenuBar mb = new MenuBar();
      		this.setMenuBar(mb);
      		Menu Breakfast = new Menu("Breakfast");
      		Menu coffee = new Menu("Coffee");
      		mb.add(Breakfast);
      		Breakfast.add(wheat = new MenuItem("Cereal"));
      		Breakfast.add(bacon = new MenuItem("Rashers"));
      		Breakfast.add(eggs = new MenuItem("Eggs"));
			// coffee is clickable submenu
         			coffee.add(hot = new CheckboxMenuItem("Hot"));
         			coffee.add(iced = new CheckboxMenuItem("Iced"));
      		Breakfast.add(coffee);
      		Breakfast.add(toast = new MenuItem("Toast"));
      
		// now do all the listeners!
      		wheat.addActionListener(new ActionListener( ){
            		public void actionPerformed(ActionEvent e)
               		{
                  			message("Cereal");
               		}
         		});
         
      		bacon.addActionListener(new ActionListener( ){
            		public void actionPerformed(ActionEvent e)
               		{
                  			message("Rashers");
               		}
         		});
      
      		eggs.addActionListener(new ActionListener( ){
            		public void actionPerformed(ActionEvent e)
               		{
                 			message("Eggs");
               		}
         		});
      
      		toast.addActionListener(new ActionListener( ){
            		public void actionPerformed(ActionEvent e)
               		{
                  			message("Toast");
               		}
         		});
         		
		// set state of other option to unchecked if hot is chosen, you
		// cannot have iced hot coffee!
      		hot.addItemListener(new ItemListener( ){
            		public void itemStateChanged(ItemEvent e)
               		{
                  			if(hot.getState( )==true)
                  			message("Hot Coffee");
                  			iced.setState(false);
               		}
         		});
         				
		// use getState to see if it has been clicked on or off
      		iced.addItemListener(new ItemListener( ){
            		public void itemStateChanged(ItemEvent e)
               		{
                  			if(iced.getState( )==true)
                  			message("Iced Coffee");
                  			hot.setState(false);
               		}
         		});
         
      		add(b);     
   		}

    		// you didnt expect a cooked breakfast did you?
   		void message(String s)
   		{
      			System.out.println("You have chosen: " + s);
   		}
   
   
   		public static void main(String[] args)
   		{
      			Frame f = new myMenuEvent( );
      			f.pack( );
      			f.show( );
   		}

}

EVENT HANDLING IN JDK1.1 - #7 DIALOGUE BOXES

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

public class myNewDialog extends Frame 
{
   	private Button b;
   	private MenuItem about;
   
   	private About a;

   	public myNewDialog( )
  	{
      		setLayout(new BorderLayout(20,20));
     		b = new Button("Quit");
      		b.addActionListener(new ActionListener( ){
         			public void actionPerformed( ActionEvent e )
         			{
            			System.exit(0);
         			}
      		});
      
      		this.addWindowListener(new WindowAdapter( ){
         			public void windowClosing(WindowEvent e)
         			{
                			System.exit(0);
         			}
      		});
      
      		MenuBar mb = new MenuBar( );
      		this.setMenuBar(mb);
      		Menu Help = new Menu("Help");
		mb.add(Help);
      		Help.add(about = new MenuItem("About"));
         
    		about.addActionListener(new ActionListener( ){
            		public void actionPerformed(ActionEvent e)
               		{
                  			a = new About(myNewDialog.this);
                  			a.show( );
               		} 
         		});
             
      		add(b);     
   	}
   
    	public static void main(String[] args)
   	{
      		Frame f = new myNewDialog( );
     		f.pack( );
      		f.show( );
   	 }
  

}


class About extends Dialog
{
   	private Button b;
   	private Label l, l1;
   	private Panel p, p1;
   
   	public About(Frame parent)
   	{
      		super(parent, "About", false);
      		b = new Button("OK");
      		p = new Panel( );
      		p1 = new Panel( );
      		l = new Label("Teach Yourself Java");
      		l1 = new Label("Chris Wright");
      
      		p.add(l);
      		p.add(l1);
      		p1.add(b);
      
      		b.addActionListener(new ActionListener( ){
         			public void actionPerformed( ActionEvent e )
         			{
            			dispose( );
         			}
      		});
      
      		this.addWindowListener(new WindowAdapter( ){
         			public void windowClosing(WindowEvent e)
         			{
            			dispose( );
         			}
      		});
      
      		add("Center", p);
      		add("South", b);
      		pack( );
      		show( );
   	}

}

EVENT HANDLING IN JDK1.1 - #8 Mouse Events

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

public class myNewCoordinates extends Applet
{
   	private int lastX, lastY;
   	private Color myColor = Color.blue;
    
   	public void init( )
   	{
      		this.setBackground(Color.red);

      		this.addMouseListener(new MouseAdapter( ){
         			public void mousePressed(MouseEvent e)
         			{
            			lastX = e.getX( );
            			lastY = e.getY( );
         			}
      		});
      			
		this.addMouseMotionListener(new MouseMotionAdapter( ){
         			public void mouseDragged(MouseEvent e)
         			{
            			Graphics g = myNewCoordinates.this.getGraphics();
            			g.setColor(myColor);
            			int x = e.getX( );
            			int y = e.getY( );
            			g.drawLine( lastX, lastY, x, y );
            			lastX = x;
            			lastY = y;
            			showStatus("Mouse is at: ("+ lastX+"," + lastY+")");
         			} // end mouseDragged
     		}); // end inner class 
   	} // end init( )
   	
} // end class definition

EVENT HANDLING IN JDK1.1 - #1 SCROLLBARS

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class myInnerScroll extends Applet
{
   	Private Panel p;
   	Private Scrollbar Temp;
   	Private Label CentLabel, FarLabel;
   	Private TextField Centin, Farout;
   	Private int f, c, answer;
   
   
   	public void init( )
   	{  
      		setLayout(new BorderLayout( ));
      
      		Temp = new Scrollbar(Scrollbar.HORIZONTAL, 0, 20, -50, 150);
      		Temp.addAdjustmentListener(new AdjustmentListener( ){
         			public void adjustmentValueChanged(AdjustmentEvent e)
         			{
            			int Scroll;
            			Scroll = Temp.getValue( );
            			convert(Scroll);
         			}
      		}); 
      		
		CentLabel = new Label("Degrees Centigrade");
      		FarLabel = new Label("Degrees Farenheit");
      		Centin = new TextField (5);     
      		Farout = new TextField(5);
      		setBackground(Color.lightGray);
      
      		p = new Panel( );
      		p.add(CentLabel);
      		p.add(Centin);
      		p.add(FarLabel);
      		p.add(Farout);
      
      		add("Center", p);
      		add("South", Temp);
      		Centin.setText("0");
      		Farout.setText("32");
   	}
      
   	public int calc( int x )
   	{
      		answer=(((9 * x)/5) + 32 );
      		return answer;
   	}
   
   	public void convert( int x)
   	{
      		System.out.println("Temp Centigrade is:"+ x);
      		Centin.setText(Integer.toString(x));
      		f = calc(x );
      		Farout.setText( Integer.toString( f ));
   	}

}

JAVA I/O - Keyboard to Screen using StringBuffer Class

Run this class with the instruction 'java Keyboard' and text that you type at the keyboard will appear on the next line after the command prompt. Carriage Return will quit the program and return you to the command prompt.

import java.io.*;

class Keyboard
{
   	public static void main(String[] args)
   	{
      		StringBuffer sb = new StringBuffer( );
      		char c;
      
      		try
         		{
			// cast integer representation to char
            		while ((c = (char)System.in.read( )) != '\n')
            		{  
				// add char to end of StringBuffer contents
               			sb.append(c);                               
            		}
                         
         		}
      		catch(Exception e)
         		{
            		System.out.println("Exception: " + e.getMessage( ) + "has occurred");
         		}

      		System.out.println(sb);      
   	}

}

JAVA I/O - Writing to a File with an Application

This program is run with the command 'java FileOut' It will save the text you type to a file called myFile.txt in the directory it is running. Note that you can only write files with an application.

import java.io.*;

class myFile
{
   	public static void main(String[] args)
   	{
      		StringBuffer sb = new StringBuffer();
      		char c;
      
  		try
         		{
            		while ((c = (char)System.in.read( )) != '\n')
            		{  
             			sb.append(c);                               
            		}
                         
         		}
      		catch(Exception e)
         		{
            		System.out.println("Exception: " + e.getMessage( ) + "has occurred");
         		}
      			
		/*  Now convert StringBuffer to a String and store in a byte Array, ready to pass to FileOutputStream. */
      		String s = sb.toString( );
      		byte[ ] buffer = s.getBytes();

      		// create a file myFile.txt and write contents of buffer to it.
      		try
		{
            		FileOutputStream out = new FileOutputStream("myFile.txt");
            		out.write(buffer);
         		}
      		catch(Exception e)
         		{
            		System.out.println("Exception: " + e.getMessage( ) + "has occurred");
        	 	}      
   	}

}

JAVA I/O - Reading from a File with an Application

This Program run from the command line with the command ' java myFile2' will read the contents of 'myFile.txt' and print it to the screen.

import java.io.*;

class myFile2 
{
    	public static void main(String[] args)
      	{         
         		File f = new File("myFile.txt");
         		int l = (int)f.length( );
         		byte[ ] buffer = new byte[l];
         		try
            	{
               		FileInputStream in = new FileInputStream("myFile.txt");
               		in.read(buffer, 0, l);                                
            	}
                         
         		catch(Exception e)
            	{
               		System.out.println("Exception: " + e.getMessage( ) + "has occurred");
            	}
            
         		String s = new String(buffer);
         		System.out.println(s);            
      	}

}

 

JAVA I/O - Using DataInputStream

This program, run with the invocation 'java Dinput' will echo text from the keyboard to the screen.

import java.io.*;

class Dinput
{
        public static void main(String[] args)
        {
                // Step 1 - InputStreamReader read = new InputStreamReader(System.in);
				// Step 2 - BufferedReader in = new BufferedReader(read);
				// Step 3 - can be shortened to:
				
				BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
				
                String s = new String( );
      
                try
                        {
                        s = in.readLine( );
                        }
                catch(Exception e)
                        {
                        System.out.println("Exception: " + e.getMessage( ) + "has occurred");
                        }

                System.out.println(s);      
        }

}
 

JAVA I/O - Using File I/O to copy File Contents

This program, run with the invocation 'java FileStream' will copy text from the file 'jabberwock.txt' (provided by you), to the file 'jabbercopy.txt' (created by the application).

import java.io.*;

class FileStream
{
   public static void main(String[] args)
   {
      try
         {
            File inFile = new File("jabberwock.txt");
            File outFile = new File("jabbercopy.txt");
            
			// for text only files use: FileReader fis = new FileReader(inFile);
			// for text only files use: FileWriter fos = new FileWriter(outFile);
			
            FileInputStream fis = new FileInputStream(inFile);
            FileOutputStream fos = new FileOutputStream(outFile);
            
            int c;
            
            while ((c = fis.read()) != -1)
               {
                  fos.write(c);
               }
            
            fis.close();
            fos.close();
          }
       catch (FileNotFoundException e)
         {
            System.out.println(e.getMessage());
         }
       catch (IOException e)
         {
            System.out.println(e.getMessage());
         }
   }
}

 

JAVA I/O - Using File I/O to copy File Contents with a to and from a Buffer

This program, run with the invocation 'java FileStream' will echo text from the file 'jabberwock.txt' (provided by you), to the file 'jabbercopy.txt' (created by the application. Note that the Buffer classes simply take InputStreamReaders and OutputStreamWriters (or classes derived from them) as parameters to their constructors

import java.io.*;

class FileStream2
{
   
   
   public static void main(String[] args)
   {  
      try
         {
            File inFile = new File("jabberwock.txt");
            File outFile = new File("jabbercopy.txt");
            
            BufferedReader in = new BufferedReader(new FileReader(inFile));
            BufferedWriter out = new BufferedWriter(new FileWriter(outFile));
            
           	int c;
			            
			    while ((c = in.read()) != -1)
			      {
				  	System.out.println(c);
			         out.write(c);
					 out.flush();
                  }
				in.close();
				out.close();
          }
		  
       catch (FileNotFoundException e)
         {
            System.out.println(e.getMessage());
         }
       catch (IOException e)
         {
            System.out.println(e.getMessage());
         }
   }
}

JAVA I/O - Keyboard to Screen using StringBuffer Class

Run this class with the instruction 'java Keyboard' and text that you type at the keyboard will appear on the next line after the command prompt. Carriage Return will quit the program and return you to the command prompt.

import java.io.*;

class Keyboard
{
   	public static void main(String[] args)
   	{
      		StringBuffer sb = new StringBuffer( );
      		char c;
      
      		try
         		{
			// cast integer representation to char
            		while ((c = (char)System.in.read( )) != '\n')
            		{  
				// add char to end of StringBuffer contents
               			sb.append(c);                               
            		}
                         
         		}
      		catch(Exception e)
         		{
            		System.out.println("Exception: " + e.getMessage( ) + "has occurred");
         		}

      		System.out.println(sb);      
   	}

}

JAVA I/O - Writing to a File with an Application

This program is run with the command 'java FileOut' It will save the text you type to a file called myFile.txt in the directory it is running. Note that you can only write files with an application.

import java.io.*;

class myFile
{
   	public static void main(String[] args)
   	{
      		StringBuffer sb = new StringBuffer();
      		char c;
      
  		try
         		{
            		while ((c = (char)System.in.read( )) != '\n')
            		{  
             			sb.append(c);                               
            		}
                         
         		}
      		catch(Exception e)
         		{
            		System.out.println("Exception: " + e.getMessage( ) + "has occurred");
         		}
      			
		/*  Now convert StringBuffer to a String and store in a byte Array, ready to pass to FileOutputStream. */
      		String s = sb.toString( );
      		byte[ ] buffer = s.getBytes();

      		// create a file myFile.txt and write contents of buffer to it.
      		try
		{
            		FileOutputStream out = new FileOutputStream("myFile.txt");
            		out.write(buffer);
         		}
      		catch(Exception e)
         		{
            		System.out.println("Exception: " + e.getMessage( ) + "has occurred");
        	 	}      
   	}

}

JAVA I/O - Reading from a File with an Application

This Program run from the command line with the command ' java myFile2' will read the contents of 'myFile.txt' and print it to the screen.

import java.io.*;

class myFile2 
{
    	public static void main(String[] args)
      	{         
         		File f = new File("myFile.txt");
         		int l = (int)f.length( );
         		byte[ ] buffer = new byte[l];
         		try
            	{
               		FileInputStream in = new FileInputStream("myFile.txt");
               		in.read(buffer, 0, l);                                
            	}
                         
         		catch(Exception e)
            	{
               		System.out.println("Exception: " + e.getMessage( ) + "has occurred");
            	}
            
         		String s = new String(buffer);
         		System.out.println(s);            
      	}

}

 

JAVA I/O - Using DataInputStream

This program, run with the invocation 'java Dinput' will echo text from the keyboard to the screen.

import java.io.*;

class Dinput
{
        public static void main(String[] args)
        {
                // Step 1 - InputStreamReader read = new InputStreamReader(System.in);
				// Step 2 - BufferedReader in = new BufferedReader(read);
				// Step 3 - can be shortened to:
				
				BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
				
                String s = new String( );
      
                try
                        {
                        s = in.readLine( );
                        }
                catch(Exception e)
                        {
                        System.out.println("Exception: " + e.getMessage( ) + "has occurred");
                        }

                System.out.println(s);      
        }

}
 

JAVA I/O - Using File I/O to copy File Contents

This program, run with the invocation 'java FileStream' will copy text from the file 'jabberwock.txt' (provided by you), to the file 'jabbercopy.txt' (created by the application).

import java.io.*;

class FileStream
{
   public static void main(String[] args)
   {
      try
         {
            File inFile = new File("jabberwock.txt");
            File outFile = new File("jabbercopy.txt");
            
			// for text only files use: FileReader fis = new FileReader(inFile);
			// for text only files use: FileWriter fos = new FileWriter(outFile);
			
            FileInputStream fis = new FileInputStream(inFile);
            FileOutputStream fos = new FileOutputStream(outFile);
            
            int c;
            
            while ((c = fis.read()) != -1)
               {
                  fos.write(c);
               }
            
            fis.close();
            fos.close();
          }
       catch (FileNotFoundException e)
         {
            System.out.println(e.getMessage());
         }
       catch (IOException e)
         {
            System.out.println(e.getMessage());
         }
   }
}

 

JAVA I/O - Using File I/O to copy File Contents with a to and from a Buffer

This program, run with the invocation 'java FileStream' will echo text from the file 'jabberwock.txt' (provided by you), to the file 'jabbercopy.txt' (created by the application. Note that the Buffer classes simply take InputStreamReaders and OutputStreamWriters (or classes derived from them) as parameters to their constructors

import java.io.*;

class FileStream2
{
   
   
   public static void main(String[] args)
   {  
      try
         {
            File inFile = new File("jabberwock.txt");
            File outFile = new File("jabbercopy.txt");
            
            BufferedReader in = new BufferedReader(new FileReader(inFile));
            BufferedWriter out = new BufferedWriter(new FileWriter(outFile));
            
           	int c;
			            
			    while ((c = in.read()) != -1)
			      {
				  	System.out.println(c);
			         out.write(c);
					 out.flush();
                  }
				in.close();
				out.close();
          }
		  
       catch (FileNotFoundException e)
         {
            System.out.println(e.getMessage());
         }
       catch (IOException e)
         {
            System.out.println(e.getMessage());
         }
   }
}

JAVA I/O - Keyboard to Screen using StringBuffer Class

Run this class with the instruction 'java Keyboard' and text that you type at the keyboard will appear on the next line after the command prompt. Carriage Return will quit the program and return you to the command prompt.

import java.io.*;

class Keyboard
{
   	public static void main(String[] args)
   	{
      		StringBuffer sb = new StringBuffer( );
      		char c;
      
      		try
         		{
			// cast integer representation to char
            		while ((c = (char)System.in.read( )) != '\n')
            		{  
				// add char to end of StringBuffer contents
               			sb.append(c);                               
            		}
                         
         		}
      		catch(Exception e)
         		{
            		System.out.println("Exception: " + e.getMessage( ) + "has occurred");
         		}

      		System.out.println(sb);      
   	}

}

JAVA I/O - Writing to a File with an Application

This program is run with the command 'java FileOut' It will save the text you type to a file called myFile.txt in the directory it is running. Note that you can only write files with an application.

import java.io.*;

class myFile
{
   	public static void main(String[] args)
   	{
      		StringBuffer sb = new StringBuffer();
      		char c;
      
  		try
         		{
            		while ((c = (char)System.in.read( )) != '\n')
            		{  
             			sb.append(c);                               
            		}
                         
         		}
      		catch(Exception e)
         		{
            		System.out.println("Exception: " + e.getMessage( ) + "has occurred");
         		}
      			
		/*  Now convert StringBuffer to a String and store in a byte Array, ready to pass to FileOutputStream. */
      		String s = sb.toString( );
      		byte[ ] buffer = s.getBytes();

      		// create a file myFile.txt and write contents of buffer to it.
      		try
		{
            		FileOutputStream out = new FileOutputStream("myFile.txt");
            		out.write(buffer);
         		}
      		catch(Exception e)
         		{
            		System.out.println("Exception: " + e.getMessage( ) + "has occurred");
        	 	}      
   	}

}

JAVA I/O - Reading from a File with an Application

This Program run from the command line with the command ' java myFile2' will read the contents of 'myFile.txt' and print it to the screen.

import java.io.*;

class myFile2 
{
    	public static void main(String[] args)
      	{         
         		File f = new File("myFile.txt");
         		int l = (int)f.length( );
         		byte[ ] buffer = new byte[l];
         		try
            	{
               		FileInputStream in = new FileInputStream("myFile.txt");
               		in.read(buffer, 0, l);                                
            	}
                         
         		catch(Exception e)
            	{
               		System.out.println("Exception: " + e.getMessage( ) + "has occurred");
            	}
            
         		String s = new String(buffer);
         		System.out.println(s);            
      	}

}

 

JAVA I/O - Using DataInputStream

This program, run with the invocation 'java Dinput' will echo text from the keyboard to the screen.

import java.io.*;

class Dinput
{
        public static void main(String[] args)
        {
                // Step 1 - InputStreamReader read = new InputStreamReader(System.in);
				// Step 2 - BufferedReader in = new BufferedReader(read);
				// Step 3 - can be shortened to:
				
				BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
				
                String s = new String( );
      
                try
                        {
                        s = in.readLine( );
                        }
                catch(Exception e)
                        {
                        System.out.println("Exception: " + e.getMessage( ) + "has occurred");
                        }

                System.out.println(s);      
        }

}
 

JAVA I/O - Using File I/O to copy File Contents

This program, run with the invocation 'java FileStream' will copy text from the file 'jabberwock.txt' (provided by you), to the file 'jabbercopy.txt' (created by the application).

import java.io.*;

class FileStream
{
   public static void main(String[] args)
   {
      try
         {
            File inFile = new File("jabberwock.txt");
            File outFile = new File("jabbercopy.txt");
            
			// for text only files use: FileReader fis = new FileReader(inFile);
			// for text only files use: FileWriter fos = new FileWriter(outFile);
			
            FileInputStream fis = new FileInputStream(inFile);
            FileOutputStream fos = new FileOutputStream(outFile);
            
            int c;
            
            while ((c = fis.read()) != -1)
               {
                  fos.write(c);
               }
            
            fis.close();
            fos.close();
          }
       catch (FileNotFoundException e)
         {
            System.out.println(e.getMessage());
         }
       catch (IOException e)
         {
            System.out.println(e.getMessage());
         }
   }
}

 

JAVA I/O - Using File I/O to copy File Contents with a to and from a Buffer

This program, run with the invocation 'java FileStream' will echo text from the file 'jabberwock.txt' (provided by you), to the file 'jabbercopy.txt' (created by the application. Note that the Buffer classes simply take InputStreamReaders and OutputStreamWriters (or classes derived from them) as parameters to their constructors

import java.io.*;

class FileStream2
{
   
   
   public static void main(String[] args)
   {  
      try
         {
            File inFile = new File("jabberwock.txt");
            File outFile = new File("jabbercopy.txt");
            
            BufferedReader in = new BufferedReader(new FileReader(inFile));
            BufferedWriter out = new BufferedWriter(new FileWriter(outFile));
            
           	int c;
			            
			    while ((c = in.read()) != -1)
			      {
				  	System.out.println(c);
			         out.write(c);
					 out.flush();
                  }
				in.close();
				out.close();
          }
		  
       catch (FileNotFoundException e)
         {
            System.out.println(e.getMessage());
         }
       catch (IOException e)
         {
            System.out.println(e.getMessage());
         }
   }
}


Other Attractions
Search Engine
Right Time
Calorie Burning
Jokes Section
Quotes
Learn Science
Recipies
Ice Cream
Tic-Tac
Typing Test
Fun
Monthly Calendar
Yearly Calendar
Java Tutorial
Home Remedies
Calorie Count
Exact age

Thanks for Visiting us

Let us Return to Home page
Home