There exist two basic types of streams:
example one ----writes to a file
import java.io.*;
class WriteTextFile
{
public static void main ( String[] args ) throws IOException
{
String fileName = "reaper.txt" ;
FileWriter writer = new FileWriter( fileName );
writer.write( "Behold her, single in the field,\n" );
writer.write( "Yon solitary Highland Lass!\n" );
writer.write( "Reaping and singing by herself;\n" );
writer.write( "Stop here, or gently pass!\n" );
writer.close();
}
}.
Example 2 shows how to copy a file. We have reduced all exception handling parts to the minimum in order to concentrate on the new input and output primitives.
import java.io.*; public class FileCopy1{ public static void main(String[] args) throws IOException{ File inp = new File("reaper.txt"); File outp = new File("reapercopy.txt"); FileReader in = new FileReader(inp); FileWriter out = new FileWriter(outp); int c; while( (c= in.read()) != -1) out.write(c); in.close(); out.close(); } }
The next example shows how file directories can be displayed. This time, both text files and directory files are copied line by line to the standard output. BufferedReader offers support for parsing text line structures. We wrap a BufferedReader around the FileReader to get this support. The example also shows the support for getting file lists out of a directory.
example 3 employee database
import java.io.*; import java.util.*; import corejava.*; class Employee{ Employee(String n, double s, Day d){ name = n; salary = s; hireDay = d; } Employee(){} void print() { System.out.println(name + " " + salary + " " + hireYear()); } void raiseSalary(double byPercent) { salary *= 1 + byPercent / 100; } int hireYear() { return hireDay.getYear(); } void writeData(PrintWriter os) { os.print(name+"|"); os.print(salary+"|"); os.print(hireDay.getYear()+"|"); os.print(hireDay.getMonth()+"|"); os.println(hireDay.getDay()); } void readData(BufferedReader is) throws IOException { String s = is.readLine(); StringTokenizer t = new StringTokenizer(s, "|"); name = t.nextToken(); salary = Format.atof(t.nextToken()); int y = Format.atoi(t.nextToken()); int m = Format.atoi(t.nextToken()); int d = Format.atoi(t.nextToken()); hireDay = new Day(y, m, d); } private String name; private double salary; private Day hireDay; } public class EmployeeFile{ public static void main(String[] args) { Employee[] staff = new Employee[3]; staff[0] = new Employee("Harry Hacker", 35500, new Day(1989,10,1)); staff[1] = new Employee("Carl Cracker", 75000, new Day(1987,12,15)); staff[2] = new Employee("Tony Tester", 38000, new Day(1990,3,15)); for (int i = 0; i < staff.length; i++) staff[i].raiseSalary(5.25); try { PrintWriter os = new PrintWriter(new FileWriter("employee.dat")); writeData(staff, os); os.close(); } catch(IOException e) { System.out.print("Error: " + e); System.exit(1); } try { BufferedReader is = new BufferedReader(new FileReader("employee.dat")); Employee[] in = readData(is); for (int i = 0; i < in.length; i++) in[i].print(); is.close(); } catch(IOException e) { System.out.print("Error: " + e); System.exit(1); } } static void writeData(Employee[] e, PrintWriter os){ os.println(e.length); for (int i = 0; i < e.length; i++) e[i].writeData(os); } static Employee[] readData(BufferedReader is) throws IOException { int n = Format.atoi(is.readLine()); Employee[] e = new Employee[n]; int i; for (i = 0; i < n; i++) { e[i] = new Employee(); e[i].readData(is); } return e; } }
example four a mini editor
/* This program lets the user edit short text files in a window. A "File" menu provides the following commands: New -- Clears all text from the window. Open -- Let's the user select a file and loads up to 100 lines of text form that file into the window. The previous contents of the window are lost. Save -- Let's the user specify an ouput file and saves the contents of the window in that file. Quit -- Closes the window and ends the program. This class uses the non-standard classes TextReader and MessageDialog. */ import java.io.*; import java.awt.*; import java.awt.event.*; public class TrivialEdit extends Frame implements ActionListener { public static void main(String[] args) { // The main program just opens a window belonging to this // TrivialEdit class. Then the window takes care of itself // until the program is ended with the Quit command. new TrivialEdit(); } private TextArea text; // Holds that text that is displayed in the window. public TrivialEdit() { // Add a menu bar and a TextArea to the window, and show it // on the screen. The first line of this routine calls the // constructor from the superclass to specify a title for the // window. The pack() command sets the size of the window to // be just large enough to hold its contents. super("A Trivial Editor"); setMenuBar(makeMenus()); text = new TextArea(20,60); add(text, BorderLayout.CENTER); pack(); show(); } private MenuBar makeMenus() { // Create and return a menu bar containing a single menu, the // File menu. This menu contains four commands, and each // command has a keyboard equivalent. The Frame will listen // for action events from the menu. Menu fileMenu = new Menu("File"); fileMenu.addActionListener(this); fileMenu.add( new MenuItem("New", new MenuShortcut(KeyEvent.VK_N)) ); fileMenu.add( new MenuItem("Open...", new MenuShortcut(KeyEvent.VK_O)) ); fileMenu.add( new MenuItem("Save...", new MenuShortcut(KeyEvent.VK_S)) ); fileMenu.add( new MenuItem("Quit", new MenuShortcut(KeyEvent.VK_Q)) ); MenuBar bar = new MenuBar(); bar.add(fileMenu); return bar; } public void actionPerformed(ActionEvent evt) { // This will be called when the user makes a selection from // the File menu. This routine just checks which command was // selected and calls another routine to carry out the command. String cmd = evt.getActionCommand(); if (cmd.equals("New")) doNew(); else if (cmd.equals("Open...")) doOpen(); else if (cmd.equals("Save...")) doSave(); else if (cmd.equals("Quit")) doQuit(); } private void doNew() { // Carry out the "New" command from the File menu by // by clearing all the text from the TextArea. text.setText(""); } private void doSave() { // Carry out the Save command by letting the user specify // an output file and writing the text from the TextArea // to that file. FileDialog fd; // A file dialog that let's the user specify the file. String fileName; // Name of file specified by the user. String directory; // Directory that contains the file. fd = new FileDialog(this,"Save Text to File",FileDialog.SAVE); fd.show(); fileName = fd.getFile(); if (fileName == null) { // The fileName is null if the user has canceled the file // dialog. In this case, there is nothing to do, so quit. return; } directory = fd.getDirectory(); try { // Create a PrintStream for writing to the specified // file and write the text from the window to that stream. File file = new File(directory, fileName); PrintWriter out = new PrintWriter(new FileWriter(file)); String contents = text.getText(); out.print(contents); out.close(); } catch (IOException e) { // Some error has occured while opening or closing the file. // Show an error message. new MessageDialog(this, "Error: " + e.toString()); } } private void doOpen() { // Carry out the Open command by letting the user specify // the file to be opened and reading up to 100 lines from // that file. The text from the file replaces the text // in the TextArea. FileDialog fd; // A file dialog that let's the user specify the file. String fileName; // Name of file specified by the user. String directory; // Directory that contains the file. fd = new FileDialog(this,"Load File",FileDialog.LOAD); fd.show(); fileName = fd.getFile(); if (fileName == null) { // The fileName is null if the user has canceled the file // dialog. In this case, there is nothing to do, so quit. return; } directory = fd.getDirectory(); try { // Read lines from the file until end-of-file is detected, // or until 100 lines have been read. The lines are appended // the the TextArea, with a line feed after each line. File file = new File(directory, fileName); TextReader in = new TextReader(new FileReader(file)); String line; text.setText(""); int lineCt = 0; while (lineCt < 100 && in.peek() != '\0') { line = in.getln(); text.appendText(line + '\n'); lineCt++; } if (in.eof() == false) text.appendText("\n\n********** Text truncated to 100 lines! ***********\n"); in.close(); } catch (Exception e) { // Some error has occured while opening or closing the file. // Show an error message. new MessageDialog(this, "Error: " + e.toString()); } } private void doQuit() { // Carry out the Quit command by exiting the program. System.exit(0); } } // end class TrivialEdit
/* The class MessageDialog represents a modal dialog that displays a message to the user along with one, two, or three buttons. The dialog is displayed by the constructor. The user must close the dialog by clicking on one of the buttons. After the dialog has been closed by the user, the program can determine which button the user clicked by calling the getUserAction() method. This method returns the name of the button that was clicked. Note that there are several constructors specifying from 0 to 3 button names. If no button name is specified, then there will be a single button named "OK". Note also that a non-null parent Frame must be speciifed for the dialog in the constructor. */ import java.awt.*; import java.awt.event.*; import java.util.Vector; public class MessageDialog extends Dialog implements ActionListener { private String buttonClicked; // The label of the button that the user // clicked to close this dialog. The value // is null while the dialog is open. public String getUserAction() { // Can be called after the dialog has closed to find out which // button the user has clicked on. The name of the button, // as specified in the constuctor. return buttonClicked; } public MessageDialog(Frame parent, String message) { // Make a dialog to display the message with an "OK" button. // Parent must be non-null and it is the parent frame of the dialog. this(parent,message,"OK",null,null); } public MessageDialog(Frame parent, String message, String button) { // Make a dialog to display the message with one button. // the button parameter specifies the name of the button. // (If button == null, then the name of the button will be "OK".) // Parent must be non-null and it is the parent frame of the dialog. this(parent,message,button,null,null); } public MessageDialog(Frame parent, String message, String button1, String button2) { // Make a dialog to display the message with one or two buttons // with the specified names button1 and button2. If button1 is null, // the name "OK" is used. If button2 is null, it is ignored. // Parent must be non-null and it is the parent frame of the dialog. this(parent,message,button1,button2,null); } public MessageDialog(Frame parent, String message, String button1, String button2, String button3) { // Make a dialog to display the message with one, two, or three buttons // with the specified names button1, button2 and button3. If button1 is null, // the name "OK" is used. If button2 or button3 is null, it is ignored. // Parent must be non-null and it is the parent frame of the dialog. super(parent, null,true); // modal dialog with no title setBackground(Color.white); add("Center", new MessageCanvas(message)); // The message display canvas. Panel buttonBar = new Panel(); // A panel to hold the buttons. buttonBar.setLayout(new FlowLayout(FlowLayout.RIGHT,10,10)); Button b1 = new Button( (button1 == null)? "OK" : button1 ); b1.addActionListener(this); // Button events are sent to this dialog. buttonBar.add(b1); if (button2 != null) { Button b2 = new Button(button2); b2.addActionListener(this); buttonBar.add(b2); } if (button3 != null) { Button b3 = new Button(button3); b3.addActionListener(this); buttonBar.add(b3); } add("South",buttonBar); pack(); // Resize the window to its preferred size. // Then move the window to a point 50 pixles over and 30 pixels // down from teh location of its parent frame. setLocation(parent.getLocation().x+50,parent.getLocation().y+30); show(); // make the dialog visible. } public Insets getInsets() { // Allow some space around the edges of the frame. // Note that a window might already uses insets to allow // space for the title bar and border, so it is necessary // to obtain a copy of the default insets and add to that. // (The documentation says that you aren't supposed to // modify the object returned by super.getInsets, so I // make a copy of it and modify the copy.) Insets ins = (Insets)super.getInsets().clone(); ins.left += 5; ins.right += 5; ins.bottom += 12; ins.top += 5; return ins; } public void actionPerformed(ActionEvent evt) { // Respond when the user clicks on one of the buttons by saving the // name of the button that was clicked and closing the window. buttonClicked = evt.getActionCommand(); dispose(); } // The nested class MessageCanvas displays the message passed // to it in the constructor. Unless the message is very short, // it will be broken into multiple lines. private static class MessageCanvas extends Canvas { private String message; // A copy of the message // The following data is computed in makeStringList() private Vector messageStrings; // The message broken up into lines. private int messageWidth; // The width in pixels of the message display. private int messageHeight; // The height in pixels of the message display. private Font font; // The font that will be used to display the message. private int lineHeight; // The height of one line in that font. private int fontAscent; // The font ascent of the font (disance from the // baseline to the top of a tall character.) MessageCanvas(String message) { // Constructor: store the message. if (message == null) this.message = ""; // this.message can't be null. else this.message = message; } public Dimension getPreferredSize() { // Return the message size, as determined by makeStringList(), allowing // space for a border around the message. if (messageStrings == null) makeStringList(); return new Dimension(messageWidth + 20, messageHeight + 17); } public void paint(Graphics g) { // Display the message using data stored in instance variables. if (messageStrings == null) makeStringList(); int y = (getSize().height - messageHeight)/2 + fontAscent; if (y < fontAscent) y = fontAscent; int x = (getSize().width - messageWidth)/2; if (x < 0) x = 0; g.setFont(font); for (int i = 0; i < messageStrings.size(); i++) { g.drawString( (String)messageStrings.elementAt(i), x, y); y += lineHeight; } } private void makeStringList() { // Compute all the instance variables necessary for displaying // the message. If the total width of the message in pixels // would be more than 280, break it up into several lines. messageStrings = new Vector(); font = new Font("Dialog", Font.PLAIN, 12); FontMetrics fm = getFontMetrics(font); lineHeight = fm.getHeight() + 3; fontAscent = fm.getAscent(); int totalWidth = fm.stringWidth(message); if (totalWidth <= 280) { messageStrings.addElement(message); messageWidth = 280; messageHeight = lineHeight; } else { if (totalWidth > 1800) messageWidth = Math.min(500, totalWidth/6); else messageWidth = 300; int actualWidth = 0; String line = " "; String word = ""; message += " "; // this forces word == "" after the following for loop ends. for (int i = 0; i < message.length(); i++) { if (message.charAt(i) == ' ') { if (fm.stringWidth(line + word) > messageWidth + 8) { messageStrings.addElement(line); actualWidth = Math.max(actualWidth,fm.stringWidth(line)); line = ""; } line += word; if (line.length() > 0) line += ' '; word = ""; } else { word += message.charAt(i); } } if (line.length() > 0) { messageStrings.addElement(line); actualWidth = Math.max(actualWidth, fm.stringWidth(line)); } messageHeight = lineHeight*messageStrings.size() - fm.getLeading(); messageWidth = Math.max(280,actualWidth); } } } // end nested class Message Canvas } // end class MessageDialog
tokens --- very useful
// This program uses a StringTokenizer to segment a quote into its // constituent words, and prints each word to the screen. // // This program was written to illustrate the use of: // 1) StringTokenizer import java.util.StringTokenizer; public class tokens { public static void main(String [] args) { // Create a new StringTokenizer with our quote, using the default // delimiters (whitespace) TextIO.captureStandardOutput(); StringTokenizer kitty = new StringTokenizer ("Don't mess with exams, man."); // as long as kitty hasMoreTokens(), print each token to the screen while(kitty.hasMoreTokens()) { System.out.println(kitty.nextToken()); } } }
Just run these programs. Call me when you are done to see them in jbuilder.