Download presentation
Presentation is loading. Please wait.
1
Chapter 11 and 19 in Horstmann 6th edition
Introduction Chapter 11 and 19 in Horstmann 6th edition Chapter 11 and 20 in Horstmann 5th edition Files Long-term storage of large amounts of data Persistent data exists after termination of program Files stored on secondary storage devices Magnetic disks Optical disks Magnetic tapes Sequential and random access files
2
Java views a file as a stream of bytes
Files and Streams Java views a file as a stream of bytes File ends with end-of-file marker or a specific byte number File as a stream of bytes associated with an object Java also associates streams with devices System.in, System.out, and System.err Streams can be redirected File processing with classes in package java.io FileInputStream for byte-based input from a file FileOutputStream for byte-based output to a file FileReader for character-based input from a file FileWriter for character-based output to a file
3
Java’s view of a file of n bytes.
4
Files and Streams Buffering Improves performance of I/O
Copies each output to a region of memory called a buffer Entire buffer output to disk at once One long disk access takes less time than many smaller ones A program can convert a unbuffered stream into a buffered stream using the wrapping idiom Example inputStream = new BufferedReader(new FileReader("xanadu.txt")); outputStream = new BufferedWriter(new FileWriter("characteroutput.txt"));
5
Example: reading a text file
import java.util.StringTokenizer; import java.io.*; import java.text.DecimalFormat; class InventoryItem { private String name; private int units; // number of available units of this item private float price; // price per unit of this item private DecimalFormat fmt; public InventoryItem (String itemName, int numUnits, float cost) { name = itemName; units = numUnits; price = cost; fmt = new DecimalFormat ("0.##"); } public String toString() { return name + ":\t" + units + " at " + price + " = " + fmt.format ((units * price)); Example: reading a text file
6
Example: reading a text file
public class Inventory{ // Reads data about a store inventory from an input file, // creating an array of InventoryItem objects, then prints them. public static void main (String[] args) { final int MAX = 100; InventoryItem[] items = new InventoryItem[MAX]; StringTokenizer tokenizer; String line, name, file="inventory.txt"; int units, count = 0; float price; try{ FileReader fr = new FileReader (file); BufferedReader inFile = new BufferedReader (fr); line = inFile.readLine(); while (line != null) { tokenizer = new StringTokenizer (line); name = tokenizer.nextToken(); try { units = Integer.parseInt (tokenizer.nextToken()); price = Float.parseFloat (tokenizer.nextToken()); items[count++] = new InventoryItem (name, units, price); } catch (NumberFormatException exception) { System.out.println ("Error in input. Line ignored:"); System.out.println (line); inFile.close(); Example: reading a text file
7
Example: reading a text file
for (int scan = 0; scan < count; scan++) System.out.println (items[scan]); } catch (FileNotFoundException exception) { System.out.println ("The file " + file + " was not found."); catch (IOException exception) { System.out.println (exception); Example: reading a text file
8
Example: writing a text file
import java.io.*; public class TestData { // Creates a file of test data that consists of ten lines each // containing ten integer values in the range 0 to 99. public static void main (String[] args) throws IOException { final int MAX = 10; int value; String file = "test.txt"; FileWriter fw = new FileWriter (file); BufferedWriter bw = new BufferedWriter (fw); PrintWriter outFile = new PrintWriter (bw); for (int line=1; line <= MAX; line++) { for (int num=1; num <= MAX; num++) { value = (int) (Math.random() * 100); outFile.print (value + " "); } outFile.println (); outFile.close(); System.out.println ("Output file has been created: " + file); Example: writing a text file
9
An Encryption Program (1)
File encryption: To scramble file so that it is readable only to those who know the encryption method and secret keyword To use Caesar cipher: Choose encryption key – a number between 1 and 25 that indicates the shift to be used in encrypting each byte Example: If the key is 3, replace A with D, B with E, ... To decrypt, use the negative of the encryption key Copyright © 2014 by John Wiley & Sons. All rights reserved.
10
Data Streams and Object Streams
Data streams support I/O of primitive data types Object streams support I/O of objects Most, but not all, standard classes support serialization of their objects. Object stream classes ObjectInputStream and ObjectOutputStream Output using the writeObject() method
11
Updating Sequential-Access File
Difficult to update a sequential-access file Entire file must be rewritten to change one field Only acceptable if many records being updated at once “Instant-access” applications Record must be located immediately Transaction-processing systems require rapid access The solution is Random Access Files
12
Random-Access File Random-access files
behave like a large array of bytes stored in the file system Access individual records directly and quickly Use fixed length for every record Easy to calculate record locations Insert records without destroying other data in file Figure on the next slide shows random-access file
13
Java’s view of a random-access file
14
RandomAccessFile objects
DataInputStream and DataOutputstream Reads or writes data in spot specified by file-position pointer Manipulates all data as primitive types Normally writes one object at a time to file
15
// Record class for the RandomAccessFile programs.
import java.io.*; public class Record { private int account; private String lastName; private String firstName; private double balance; public Record(int a, String f, String l, double b) { account=a; firstName=f; lastName=l; balance=b; } public Record() { account=0; firstName=null; lastName=null; balance=0; // Read a record from the specified RandomAccessFile public void read( RandomAccessFile file ) throws IOException { account = file.readInt(); byte b1[] = new byte[ 15 ]; file.readFully( b1 ); firstName = new String( b1 ); firstName=firstName.trim(); byte b2[] = new byte[ 15 ]; file.readFully( b2 ); lastName = new String( b2 ); lastName=lastName.trim(); balance = file.readDouble(); Defining a class to be used for reading and writing records to a random access file
16
// Write a record to the specified RandomAccessFile
public void write( RandomAccessFile file ) throws IOException { file.writeInt( account ); byte b1[] = new byte[ 15 ]; if ( firstName != null ) b1 = firstName.getBytes(); file.write( b1 ); byte b2[] = new byte[ 15 ]; if ( lastName != null ) b2 = lastName.getBytes(); file.write( b2 ); file.writeDouble( balance ); } public void setAccount(int a) { account=a;} public void setLastName(String l) { lastName=l;} public void setFirstName(String f) { firstName=f;} public void setBalance(double b) { balance=b; } public int getAccount(){ return account;} public String getlName(){ return lastName;} public String getfName(){ return firstName;} public double getBalance(){ return balance;} public int size() { return 42; }
17
import java.io.*; public class CreateRandFile { private Record blank; RandomAccessFile file; public CreateRandFile() { blank = new Record(); try { file = new RandomAccessFile( "credit.dat", "rw" ); } catch( IOException e ) { System.err.println( "File not opened properly\n" + e.toString() ); System.exit( 1 ); public void create() { for ( int i = 0; i < 100; i++ ) blank.write( file ); catch ( IOException e ) { System.err.println( e.toString() ); public static void main( String args[] ) { CreateRandFile accounts = new CreateRandFile(); accounts.create(); This program creates a random access file sequentially by writing 100 empty records to disk.
18
import java.io.*; import java.awt.*; import javax.swing.*; import java.awt.event.*; public class WriteRandFile extends JFrame { // Application window components JTextField acct, // where user enters account number fName, // where user enters first name lName, // where user enters last name bal; // where user enters balance JButton enter, // send record to file done; // quit program JLabel acctLabel, // account label fNameLabel, // first name label lNameLabel, // last name label balLabel; // balance label RandomAccessFile output; // file for output Record data; public WriteRandFile() { super( "Write to random access file" ); data = new Record(); try { output = new RandomAccessFile( "credit.dat", "rw" ); } catch ( IOException e ) { System.err.println( e.toString() ); System.exit( 1 ); This program uses TextFields to get information from the user at the keyboard and writes the information to a random access file.
19
Container c = getContentPane();
c.setLayout( new GridLayout( 5, 2 ) ); acct = new JTextField( 20 ); acctLabel = new JLabel( "Account Number" ); fName = new JTextField( 20 ); fNameLabel = new JLabel( "First Name" ); lName = new JTextField( 20 ); lNameLabel = new JLabel( "Last Name" ); bal = new JTextField( 20 ); balLabel = new JLabel( "Balance" ); enter = new JButton( "Enter" ); done = new JButton( "Done" ); c.add( acctLabel ); // add label c.add( acct ); // add TextField c.add( fNameLabel ); // add label c.add( fName ); // add TextField c.add( lNameLabel ); // add label c.add( lName ); // add TextField c.add( balLabel ); // add label c.add( bal ); // add TextField c.add( enter ); // add button c.add( done ); // add button done.addActionListener( new ActionListener () { public void actionPerformed( ActionEvent event ){ System.exit( 0 ); } } );
20
enter.addActionListener(
new ActionListener () { public void actionPerformed( ActionEvent event ){ addRecord(); } } ); setSize( 300, 150 ); setVisible( true ); } public static void main( String args[] ) { WriteRandFile accounts = new WriteRandFile();
21
data.setBalance(Double.parseDouble(bal.getText()));
public void addRecord() { int acctNum = 0; Double d; acctNum = ( new Integer( acct.getText() ) ).intValue(); // output the values to the file try { if ( acctNum > 0 && acctNum <= 100 ) { data.setAccount(acctNum); data.setFirstName(fName.getText()); data.setLastName(lName.getText()); data.setBalance(Double.parseDouble(bal.getText())); output.seek( (long) ( acctNum-1 ) * data.size() ); data.write( output ); // clear the TextFields acct.setText( "" ); fName.setText( "" ); lName.setText( "" ); bal.setText( "" ); } else { acct.setText( "Enter valid account (1-100)" ); acct.selectAll(); catch ( IOException e ) { System.err.println( "Error during write to file\n" + e.toString() ); System.exit( 1 );
22
import java.io.*; import java.awt.*; import javax.swing.*; import java.awt.event.*; public class ReadRandFile extends JFrame { // Application window components JTextField acct, // where user enters account number fName, // where user enters first name lName, // where user enters last name bal; // where user enters balance JButton next, // send record to file done; // quit program JLabel acctLabel, // account label fNameLabel, // first name label lNameLabel, // last name label balLabel; // balance label RandomAccessFile input; // file for output Record data; boolean moreRecords=true; public ReadRandFile() { super( "Write to random access file" ); data = new Record(); try { input = new RandomAccessFile( "credit.dat", "r" ); } catch ( IOException e ) { System.err.println( e.toString() ); System.exit( 1 ); This program opens a random-access file and displays only the records with data.
23
Container c = getContentPane();
c.setLayout( new GridLayout( 5, 2 ) ); acct = new JTextField( 20 ); acctLabel = new JLabel( "Account Number" ); fName = new JTextField( 20 ); fNameLabel = new JLabel( "First Name" ); lName = new JTextField( 20 ); lNameLabel = new JLabel( "Last Name" ); bal = new JTextField( 20 ); balLabel = new JLabel( "Balance" ); next = new JButton( "Next" ); done = new JButton( "Done" ); c.add( acctLabel ); // add label c.add( acct ); // add TextField c.add( fNameLabel ); // add label c.add( fName ); // add TextField c.add( lNameLabel ); // add label c.add( lName ); // add TextField c.add( balLabel ); // add label c.add( bal ); // add TextField c.add( next ); // add button c.add( done ); // add button This program opens a random-access file and displays only the records with data.
24
done.addActionListener(
new ActionListener () { public void actionPerformed( ActionEvent event ){ System.exit( 0 ); } } ); next.addActionListener( readRecord(); setSize( 300, 150 ); setVisible( true ); } public static void main( String args[] ) { ReadRandFile accounts = new ReadRandFile();
25
public void readRecord() {
try { do { // loop over empty records data.read( input ); } while ( input.getFilePointer() < input.length() && data.getAccount() == 0 ); } catch( IOException e ) { moreRecords = false; // transfer full record data into textfields if ( data.getAccount() != 0 ) { acct.setText( String.valueOf( data.getAccount() ) ); String fN=data.getfName(); fName.setText( fN); String lN=data.getlName(); lName.setText( lN ); bal.setText( String.valueOf( data.getBalance() ) );
26
Exercise Write a Java applet which reads the random access file “credit.dat”, enters the non-blanc records into an array of Records, sorts the array with the last names in ascending order and displays names and balances in a text area. The GUI of this applet contains just the button “Display All” and the text area.
27
Solution // this program reads a random access file and displays the clients names and their balances with the last names in alphabetic order import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.io.*; import java.util.*; public class ListRecords extends JApplet implements ActionListener{ Record[] cust; Record data; String s=""; int jj=0, acct; JButton b1; JTextArea ta; public void init() { cust = new Record[100]; data = new Record(); try { RandomAccessFile file = new RandomAccessFile( "credit.dat", "r" ); for (int i=1; i<100; i++) { data.read( file ); if (data.getAccount() !=0 ) cust[jj++]= new Record(data.getAccount(),data.getLastName(),data.getFirstName(),data.getBalance()); } } catch ( IOException e ) { System.exit( 1 ); }
28
Solution (continue) // GUI and event processing Container c = getContentPane(); c.setLayout(new BorderLayout()); // this is optional b1=new JButton("Display All"); b1.addActionListener(this); c.add(b1, BorderLayout.NORTH); ta = new JTextArea(20, 20); c.add(new JScrollPane(ta), BorderLayout.SOUTH); } public void actionPerformed(ActionEvent e) { sort(); for (int i=0; i<jj; i++) s+=cust[i].getLastName()+" has=$"+ cust[i].getBalance() + "\n"; ta.setText(s); public void sort() { for ( int pass = 1; pass < jj; pass++ ) { for ( int element = 0; element < jj - 1; element++ ) { if ( cust[element].getLastName().compareTo(cust[element+1].getLastName())>0 ) swap(element,element+1); prublic void swap(int i, int j) { Record temp = cust[i]; cust[i] = cust[j]; cust[j] = temp;
29
Application: Transaction Processing
Substantial transaction-processing system Uses random-access file Updates, adds and deletes accounts
30
Client-Server Interaction with Stream Socket Connections – ch
Client-Server Interaction with Stream Socket Connections – ch.23 in Horstmann 6th ed. The following example uses stream sockets to demonstrate a simple client/server chat application. In these example one has to run both the client and the server, with the server being the first to be executed. Establishing a simple server requires 5 steps: the creation of a ServerSocket object (constructor needs the port number and max number of clients), the call to ServerSocket’s method accept(), which provides a Socket object when the connection to a client is established creation of OutputStream and InputStream objects for communication through the Socket. the processing phase in which both the server and the client send their information the closing of the communication In this example the client will ask the server for the definition of a word and the communication will be done using the methods writeUTF() and readUTF() of OutputStream and InputStream (these methods use unformatted sets of bytes). Note that the lines: DataInputStream dis = new DataInputStream(s.getInputStream()); DataOutputStream dos = new DataOutputStream(s.getOutputStream()); provide an automatic 2-ways communication channel.
31
// Simple internet server - one client at a time
import java.net.*; import java.io.*; class Server1 { public static void main(String args[]) { ServerSocket ss = null; boolean good = true; try { ss = new ServerSocket(21345); // allows for a single client at port 21345 } catch (IOException e) { System.out.println("Cannot create server"); good = false; } while (good) { Socket s = null; s = ss.accept(); System.out.println("New client started"); System.out.println("Fatal server error number"); if (good) { DataInputStream dis = new DataInputStream(s.getInputStream()); DataOutputStream dos = new DataOutputStream(s.getOutputStream()); boolean keepgoing = true;
32
while (keepgoing) { String str = dis.readUTF(); if (str.equals(""))
keepgoing = false; else { dos.writeUTF(lookup(str)); dos.flush(); } s.close(); System.out.println("Client terminated"); } catch (IOException e) { System.out.println("Client aborted prematurely"); System.exit(1); static String lookup(String word) { String rc = "Sorry - no definition for that word"; if (word.equalsIgnoreCase("socket")) rc = "logical connection between two computers"; else if (word.equalsIgnoreCase("server")) rc = "program that services request through the Internet"; return rc;
33
import java.io.*; import java.net.*; public class Client1 { public static void main(String args[]) { Socket s = null; boolean good = true; DataInputStream dis = null; DataOutputStream dos = null; try { s = new Socket("localhost", 21345); dis = new DataInputStream(s.getInputStream()); dos = new DataOutputStream(s.getOutputStream()); } catch (IOException e) { System.out.println("Cannot create Socket"); good = false; }
34
if (good) { String word; boolean done = false; do { byte buffer[] = new byte [100]; System.out.println("Enter a word to define: "); try { System.in.read(buffer); word = new String(buffer); word = word.trim(); dos.writeUTF(word); dos.flush(); if (word.equals("")) done = true; else System.out.println(dis.readUTF()); } catch (IOException e) { System.out.println("Socket has died"); } } while (!done);
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.