Question: Update the program with the character streams for the employee name and number from the keyboard to an output file. Use binary streams of strings
Update the program with the character streams for the employee name and number from the keyboard to an output file. Use binary streams of strings and integers.
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class frameread extends JFrame
implements ActionListener, WindowListener
{
JTextField name = new JTextField(20);
JTextField hr = new JTextField(5);
JButton enter = new
JButton("View next player data");
JLabel namelab= new JLabel("Player Name");
JLabel hrlab = new JLabel("Home Runs");
DataInputStream istream;
Container c = getContentPane();
public frameread()
{
super("Read Players File");
try
{
istream = new
DataInputStream(new FileInputStream("players.txt"));
// chain istream to file
}
catch(IOException e)
{
System.err.println("File not opened");
System.exit(1);
}
setSize(250,200);
c.setLayout(new FlowLayout());
c.add(namelab);
c.add(name);
c.add(hrlab);
c.add(hr);
c.add(enter);
enter.requestFocus();
addWindowListener(this);
enter.addActionListener(this);
} // actionPerformed continued
public void actionPerformed(ActionEvent e1)
{
try
{
name.setText(istream.readUTF());
/* read a String from file associated to istream and set it to the name TextField */
hr.setText(String.valueOf(istream.readInt()));
/* read an integer from file associated to istream and set it to the hr TextField */
}
catch(EOFException e2)
{
closeFile(); // if try to view past the EOF
}
catch(IOException e3)
{
System.err.println("Error reading file");
System.exit(1);
}
}
public void closeFile()
{
try
{
istream.close();
System.exit(0);
}
catch(IOException e)
{
System.err.println("Error closing file");
System.exit(1);
}
}
// window methods continued
public void windowClosing(WindowEvent e)
{
try
{
istream.close(); // close file with frame window
}
catch(IOException e2)
{
System.err.println("File already closed");
System.exit(1);
}
System.exit(0);
}
public void windowClosed(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
}
And the main class:
import java.io.*;
public class framereadmain
{
public static void main(String[] args)
{
frameread f = new frameread();
f.setVisible(true);
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
