BuiltWithNOF
Files in Java

import java.awt.*;
import java.awt.event.*;
import java.io.*;
//import javax.swing.*;

public class LoadSave extends Frame
{
static int age[];
static String name[];
static double gpa[];
static Button btnAdd,btnPrint,btnSave,btnLoad;
static Label l;
static List list;
static TextField t1,t2,t3;
static int arrayCount;
static DataOutputStream dout;
static DataInputStream din;

public LoadSave()
{
super("Load and Save Example");
Panel top = new Panel();
top.setLayout(null);

arrayCount = 0;
name = new String[100];
age = new int[100];
gpa = new double[100];

btnAdd = new Button("Add");
btnPrint = new Button("Print");
btnSave = new Button("Save");
btnLoad = new Button("Load");
top.add(btnAdd);
top.add(btnPrint);
top.add(btnSave);
top.add(btnLoad);
btnAdd.setBounds(300,10,50,30);
btnPrint.setBounds(300,50,50,30);
btnSave.setBounds(300,90,50,30);
btnLoad.setBounds(300,130,50,30);

list = new List(10); top.add(list);
list.setBounds(300,170,100,200);

l = new Label("Enter Name, Age and GPA");
t1 = new TextField(10);
t2 = new TextField(10);
t3 = new TextField(10);

add(top);
top.setBackground(Color.lightGray);

top.add(l);
top.add(t1); top.add(t2); top.add(t3);

l.setBounds(10,10,150,20);
t1.setBounds(10,40,80,20);
t2.setBounds(10,70,80,20);
t3.setBounds(10,100,80,20);
setSize(600,400);
show();
}

public void paint( Graphics g )
{
g.drawString("put this here",100,50);
}

public static void main(String args[])
{
//c=0;
LoadSave t = new LoadSave();
t.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
}


public boolean action(Event e, Object o)
{
if (e.target==btnAdd)
{
name[arrayCount]=t1.getText();
age[arrayCount] = Integer.parseInt(t2.getText());
gpa[arrayCount] = Double.parseDouble(t3.getText());
arrayCount++;

t1.setText(""); t2.setText(""); t3.setText("");
}

if (e.target == btnPrint)
{
for (int x=0; x<arrayCount; x++)
{
list.addItem(name[x]+" " + String.valueOf(age[x])+" "+String.valueOf(gpa[x]));
}
arrayCount = 0;
}

if (e.target == btnSave)
{
SaveFile("C:/Junker.dmo");
}

if (e.target == btnLoad)
{
LoadFile("C:/Junker.dmo");
}

return true;
}


public void SaveFile(String fname)
{
try
{
dout = new DataOutputStream(new FileOutputStream(fname));
}
catch (IOException e) { System.out.println("no such file");}

try
{
for (int x=0;x<arrayCount;x++)
dout.writeBytes(name[x]+ String.valueOf(age[x])+'\n');
}
catch (IOException e) {System.out.println(e.toString());}

}


public void LoadFile(String fname)
{
try
{
din = new DataInputStream(new FileInputStream(fname));
}
catch (IOException e) { System.out.println("no such file");}

try
{
String tmp="";
while( (tmp=din.readLine()) != null)
{ // add each item to list untill MT
list.addItem(tmp);
}
}
catch (IOException e) {System.out.println("123" + e.toString());}
}
}

 

[Home] [Syllabus] [Sessions]