diff --git a/.idea/libraries/17_4.xml b/.idea/libraries/17_4.xml new file mode 100644 index 0000000..703ea02 --- /dev/null +++ b/.idea/libraries/17_4.xml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/11.5_StackUnwinding/src/UsingExceptions.java b/11.5_StackUnwinding/src/UsingExceptions.java index efacad6..6d71dc5 100644 --- a/11.5_StackUnwinding/src/UsingExceptions.java +++ b/11.5_StackUnwinding/src/UsingExceptions.java @@ -3,7 +3,7 @@ public class UsingExceptions { - public static void main(String[] args) + public static void main(String[] args) // aoeuaoe { try { diff --git a/17.3 FileDemonstration/src/FileDemonstration.java b/17.3 FileDemonstration/src/FileDemonstration.java index 2df50ac..ed14776 100644 --- a/17.3 FileDemonstration/src/FileDemonstration.java +++ b/17.3 FileDemonstration/src/FileDemonstration.java @@ -31,7 +31,7 @@ public static void analyzePath(String path) (name.isDirectory() ? "is a directory" : "is not a directory"), (name.isAbsolute() ? "is absolute path" : "is not absolute path"), "Last modified: ", - name.lastModified(), "Lengeth: ", name.length(), + name.lastModified(), "Length: ", name.length(), "Path: ", name.getPath(), "Absolute path: ", name.getAbsolutePath(), "Parent: ", name.getParent()); diff --git a/17.4 Sequential-Access Text Files/17.4 Sequential-Access Text Files.iml b/17.4 Sequential-Access Text Files/17.4 Sequential-Access Text Files.iml index 0748b98..3445f21 100644 --- a/17.4 Sequential-Access Text Files/17.4 Sequential-Access Text Files.iml +++ b/17.4 Sequential-Access Text Files/17.4 Sequential-Access Text Files.iml @@ -1,11 +1,16 @@ + + - + - + + + + \ No newline at end of file diff --git a/17.4 Sequential-Access Text Files/src/CaseStudy/CreditInquiry.java b/17.4 Sequential-Access Text Files/src/CaseStudy/CreditInquiry.java new file mode 100644 index 0000000..a686232 --- /dev/null +++ b/17.4 Sequential-Access Text Files/src/CaseStudy/CreditInquiry.java @@ -0,0 +1,144 @@ +// Fig. 17.12: CreditInquiry.java +// This program reads a file sequentially and displays the +// content based on the type of account the user requests +// (credit balance, debit balance or zero balance). +package CaseStudy; +import java.io.File; +import java.io.FileNotFoundException; +import java.lang.IllegalStateException; +import java.nio.channels.IllegalSelectorException; +import java.util.NoSuchElementException; +import java.util.Scanner; +import SequentialFile.AccountRecord; +import com.sun.org.apache.bcel.internal.generic.MONITORENTER; + +import javax.accessibility.AccessibleTable; + + +public class CreditInquiry +{ + private MenuOption accountType; + private Scanner input; + private final static MenuOption[] choices = {MenuOption.ZERO_BALANCE, MenuOption.CREDIT_BALANCE, + MenuOption.DEBIT_BALANCE, MenuOption.END}; + + // read records from file and display only records of appropriate type + private void readRecords() + { + // object to store data that will be written to file + AccountRecord record = new AccountRecord(); + + try // read records + { + // open file to read from beginning + input = new Scanner(new File("clients.txt")); + + while (input.hasNext()) // input the values from the file + { + record.setAccount(input.nextInt()); // read account number + record.setFirstName(input.next()); // read first name + record.setLastName(input.next()); // read last name + record.setBalance((input.nextDouble())); // read balance + + // if proper account type, display record + if (shouldDisplay(record.getBalance())) + System.out.printf("%-10d%-12s%-12s%10.2f\n", + record.getAccount(), record.getFirstName(), + record.getLastName(), record.getBalance()); + } // end while + } // end try + catch (NoSuchElementException elementException) + { + System.err.println("File improperly formed."); + input.close(); + System.exit(1); + } // end catch + catch (IllegalStateException stateException) + { + System.err.println("Error reading from file."); + System.exit(1); + } // end catch + catch (FileNotFoundException fileNotFoundException) + { + System.err.println("File cannot be found."); + System.exit(1); + } // end catch + finally + { + if (input != null) + input.close(); // close the Scanner and the file + } // end finally + } // end method readRecords + + // use record type to determine if record should be displayed + private boolean shouldDisplay(double balance) + { + if (( accountType == MenuOption.CREDIT_BALANCE) + && (balance < 0)) + return true; + else if ((accountType == MenuOption.DEBIT_BALANCE) + && (balance > 0)) + return true; + else if ((accountType == MenuOption.ZERO_BALANCE) + && (balance == 0)) + return true; + + return false; + } // end method shouldDisplay + + // obtain request from user + private MenuOption getRequest() + { + Scanner textIn = new Scanner(System.in); + int request = 1; + + // display request options + System.out.printf("\n%s\n%s\n%s\n%s\n%s\n", + "Enter request", " 1 - List accounts with zero balances", + " 2 - List accounts with credit balances", + " 3 - List accounts with debit balances", + " 4 - End of run"); + + try // attempt to input new menu choice + { + do // input user request + { + System.out.print("\n? "); + request = textIn.nextInt(); + } + while ((request < 1) || request > 4); + } // end try + catch (NoSuchElementException elementException) + { + System.err.println("Invalid input."); + System.exit(1); + } // end catch + + return choices[request - 1]; // return enum value for option + } // end method getRequest + + public void processRequests() + { + // get user's request (e.g., zero, credit or debit balance) + accountType = getRequest(); + + while (accountType != MenuOption.END) + { + switch (accountType) + { + case ZERO_BALANCE: + System.out.println("\nAccounts with zero balance:\n"); + break; + case CREDIT_BALANCE: + System.out.println("\nAccounts with credit balances:\n"); + break; + case DEBIT_BALANCE: + System.out.println("\nAccounts with debit balances:\n"); + break; + } // end switch + + readRecords(); + accountType = getRequest(); + } // end while + } // etd method processRequests +} // end class CreditInquiry diff --git a/17.4 Sequential-Access Text Files/src/CaseStudy/CreditInquiryTest.java b/17.4 Sequential-Access Text Files/src/CaseStudy/CreditInquiryTest.java new file mode 100644 index 0000000..e5910c6 --- /dev/null +++ b/17.4 Sequential-Access Text Files/src/CaseStudy/CreditInquiryTest.java @@ -0,0 +1,13 @@ +package CaseStudy; + +/** + * Created by P Trang on 8/3/2015. + */ +public class CreditInquiryTest +{ + public static void main(String[] args) + { + CreditInquiry application = new CreditInquiry(); + application.processRequests(); + } // end main +} // end class CreditInquiryTest diff --git a/17.4 Sequential-Access Text Files/src/CaseStudy/MenuOption.java b/17.4 Sequential-Access Text Files/src/CaseStudy/MenuOption.java new file mode 100644 index 0000000..a0c54fc --- /dev/null +++ b/17.4 Sequential-Access Text Files/src/CaseStudy/MenuOption.java @@ -0,0 +1,27 @@ +package CaseStudy; + +// Fig. 17.11: MenuOption.java +// Enumeration for the credit-inquiry program's options. + +public enum MenuOption +{ + // declare contents of enum type + ZERO_BALANCE(1), + CREDIT_BALANCE(2), + DEBIT_BALANCE(3), + END(4); + + private final int value; // current menu option + + // constructor + MenuOption(int valueOption) + { + value = valueOption; + } // end MenuOptions enum constructor + + // return the value of a constant + public int getValue() + { + return value; + } // end method getValue +} // end enum MenuOption diff --git a/17.4 Sequential-Access Text Files/src/AccountRecord.java b/17.4 Sequential-Access Text Files/src/SequentialFile/AccountRecord.java similarity index 83% rename from 17.4 Sequential-Access Text Files/src/AccountRecord.java rename to 17.4 Sequential-Access Text Files/src/SequentialFile/AccountRecord.java index 19f289b..aec1245 100644 --- a/17.4 Sequential-Access Text Files/src/AccountRecord.java +++ b/17.4 Sequential-Access Text Files/src/SequentialFile/AccountRecord.java @@ -1,9 +1,11 @@ +package SequentialFile; + /** - * Fig. 17.4: AccountRecord.java - * AccountRecord class maintains information for one account. + * Fig. 17.4: SequentialFile.AccountRecord.java + * SequentialFile.AccountRecord class maintains information for one account. */ -public class AccountRecord // testuaoeuoa +public class AccountRecord { private int account; private String firstName; @@ -23,7 +25,7 @@ public AccountRecord(int acct, String first, String last, double bal) setFirstName(first); setLastName(last); setBalance(bal); - } // end four-argument AccountRecord constructor + } // end four-argument SequentialFile.AccountRecord constructor // set account number public void setAccount(int acct) @@ -72,4 +74,4 @@ public double getBalance() { return balance; } // end method getBalance -} // end class AccountRecord \ No newline at end of file +} // end class SequentialFile.AccountRecord \ No newline at end of file diff --git a/17.4 Sequential-Access Text Files/src/CreateTextFile.java b/17.4 Sequential-Access Text Files/src/SequentialFile/CreateTextFile.java similarity index 96% rename from 17.4 Sequential-Access Text Files/src/CreateTextFile.java rename to 17.4 Sequential-Access Text Files/src/SequentialFile/CreateTextFile.java index 594a1c7..eecf3b2 100644 --- a/17.4 Sequential-Access Text Files/src/CreateTextFile.java +++ b/17.4 Sequential-Access Text Files/src/SequentialFile/CreateTextFile.java @@ -1,7 +1,8 @@ /** - * Fig. 17.5: CreateTextFile.java + * Fig. 17.5: SequentialFile.CreateTextFile.java * Writing data to a sequential text file with class Formatter. */ +package SequentialFile; import java.io.FileNotFoundException; import java.lang.SecurityException; @@ -97,4 +98,4 @@ public void closeFile() if (output != null) output.close(); } // end method closeFile -} // end class CreateTextFile \ No newline at end of file +} // end class SequentialFile.CreateTextFile \ No newline at end of file diff --git a/17.4 Sequential-Access Text Files/src/SequentialFile/CreateTextFileTest.java b/17.4 Sequential-Access Text Files/src/SequentialFile/CreateTextFileTest.java new file mode 100644 index 0000000..87ca4e4 --- /dev/null +++ b/17.4 Sequential-Access Text Files/src/SequentialFile/CreateTextFileTest.java @@ -0,0 +1,13 @@ +package SequentialFile;// Testing the SequentialFile.CreateTextFile class + +public class CreateTextFileTest +{ + public static void main(String[] args) + { + CreateTextFile application = new CreateTextFile(); + + application.openFile(); + application.addRecords(); + application.closeFile(); + } // end main +} // diff --git a/17.4 Sequential-Access Text Files/src/SequentialFile/ReadTextFile.java b/17.4 Sequential-Access Text Files/src/SequentialFile/ReadTextFile.java new file mode 100644 index 0000000..9b7e7e5 --- /dev/null +++ b/17.4 Sequential-Access Text Files/src/SequentialFile/ReadTextFile.java @@ -0,0 +1,73 @@ +package SequentialFile; /** + * Fig. 17.9: SequentialFile.ReadTextFile.java + * This program reads a text files and displays each record. + */ +import java.io.File; +import java.io.FileNotFoundException; +import java.lang.IllegalStateException; +import java.util.NoSuchElementException; +import java.util.Scanner; + +public class ReadTextFile +{ + private Scanner input; + + // enable user to open file + public void openFile() + { + try + { + input = new Scanner(new File("clients.txt")); + } // end try + catch(FileNotFoundException fileNotFoundException) + { + System.err.println("Error opening file."); + System.exit(1); + } // end catch + } // end method openFile + + // read record from file + public void readRecords() + { + // object to be written to screen + AccountRecord record = new AccountRecord(); + + System.out.printf("%-10s%-12s%-12s%10s\n", "Account", + "First Name", "Last Name", "Balance"); + try // read records from files using Scanner object + { + while (input.hasNext()) + { + record.setAccount(input.nextInt()); // read account number + record.setFirstName(input.next()); // read first name + record.setLastName(input.next()); // read last name + record.setBalance(input.nextDouble()); // read balance + + // display record contents + System.out.printf("%-10d%-12s%-12s%10.2f\n", + record.getAccount(), record.getFirstName(), + record.getLastName(), record.getBalance()); + } // end while + } // end try + catch (NoSuchElementException elementException) + { + System.err.println("File improperly formed."); + input.close(); + System.exit(1); + } // end catch + catch (IllegalStateException stateException) + { + System.err.println("Error reading from file."); + System.exit(1); + } // end catch + } // end method readRecords + + // close files and terminate application + public void closeFile() + { + if (input != null) + { + input.close(); // close file + } + } // end method closeFile +} // end class SequentialFile.ReadTextFile diff --git a/17.4 Sequential-Access Text Files/src/SequentialFile/ReadTextFileTest.java b/17.4 Sequential-Access Text Files/src/SequentialFile/ReadTextFileTest.java new file mode 100644 index 0000000..de840d3 --- /dev/null +++ b/17.4 Sequential-Access Text Files/src/SequentialFile/ReadTextFileTest.java @@ -0,0 +1,13 @@ +package SequentialFile;// Testing the SequentialFile.ReadTextFile class. + +public class ReadTextFileTest +{ + public static void main(String[] args) + { + ReadTextFile application = new ReadTextFile(); + + application.openFile(); + application.readRecords(); + application.closeFile(); + } // end main +} // end class ReadTexFileTest diff --git a/17.5 Object Serialization/17.5 Object Serialization.iml b/17.5 Object Serialization/17.5 Object Serialization.iml new file mode 100644 index 0000000..bd4694b --- /dev/null +++ b/17.5 Object Serialization/17.5 Object Serialization.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/17.5 Object Serialization/src/AccountRecordSerializable.java b/17.5 Object Serialization/src/AccountRecordSerializable.java new file mode 100644 index 0000000..2f0e534 --- /dev/null +++ b/17.5 Object Serialization/src/AccountRecordSerializable.java @@ -0,0 +1,78 @@ +/** + * Fig. 17.15: AccountRecordSerializable.java + * AccountRecordSerializable class for serializable objects. + */ + +import java.io.Serializable; + +public class AccountRecordSerializable implements Serializable +{ + private int account; + private String firstName; + private String lastName; + private double balance; + + // no-argument constructor calls other constructor with default values. + public AccountRecordSerializable() + { + this(0, "", "", 0.0); + } // end no-argument AccountRecordSerializable constructor + + // four-argument constructor initializes a record + public AccountRecordSerializable( + int acct, String first, String last, double bal) + { + setAccount(acct); + setFirstName(first); + setLastName(last); + setBalance(bal); + } // end four-argument AccountRecordSerializable constructor + + // set account number + public void setAccount(int acct) + { + account = acct; + } // end method setAccount + + // get account number + public int getAccount() + { + return account; + } // end method getAccount + + // set first name + public void setFirstName(String first) + { + firstName = first; + } // end method setFirstName + + // get first name + public String getFirstName() + { + return firstName; + } // end method getFirstName + + // set last name + public void setLastName(String last) + { + lastName = last; + } // end method setLastName + + // get last name + public String getLastName() + { + return lastName; + } // end method getLastName + + // set balance + public void setBalance(double bal) + { + balance = bal; + } // end method setBalance + + // get balance + public double getBalance() + { + return balance; + } // end method getBalance +} // end class AccountRecordSerializable diff --git a/17.5 Object Serialization/src/CreateSequentialFile.java b/17.5 Object Serialization/src/CreateSequentialFile.java new file mode 100644 index 0000000..efa3e46 --- /dev/null +++ b/17.5 Object Serialization/src/CreateSequentialFile.java @@ -0,0 +1,100 @@ +// Fig. 17.16: CreateSequentialFile.java +// Writing objects sequentially to a file with class ObjectOutputStream +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectOutputStream; +import java.util.NoSuchElementException; +import java.util.Scanner; + + +public class CreateSequentialFile +{ + private ObjectOutputStream output; // outputs data to file + // allow user to specify file name + public void openFile() + { + try // open file + { + output = new ObjectOutputStream(new FileOutputStream("clients.ser")); + } // end try + catch (IOException ioException) + { + System.err.println("Error opening flie."); + } // end catch + } // end method openFlie + + // add records to file + public void addRecords() + { + AccountRecordSerializable record; // object to be written to file + int accountNumber = 0; // account number for record object. + String firstName; // first name for record object + String lastName; // last name for record object + double balance; // balance for record object + + Scanner input = new Scanner(System.in); + + System.out.printf("%s\n%s\n%s\n%s\n\n", + "To terminate input, tye the end-of-file indicator ", + "when you are prompted to enter input.", + "On UNIX/Linux/Mac OS X type d then press Enter", + "On Windows type z then press enter"); + + System.out.printf("%s\n%s", + "Enter account number (> 0), first name, last name, and balance.", + "? "); + + while (input.hasNext()) // loop until end-of-file indicator + { + try // output values to file + { + accountNumber = input.nextInt(); // read account number + firstName = input.next(); // read first name + lastName = input.next(); // read last name + balance = input.nextDouble(); // read balance + + if (accountNumber > 0) + { + // create new record + record = new AccountRecordSerializable(accountNumber, firstName, lastName, balance); + output.writeObject(record); // output record + } // end if + else + { + System.out.println( + "Account number must be greater than 0."); + } // end else + } // end try + catch(IOException ioException) + { + System.err.println("Error writing to file."); + return; + } // end catch + catch(NoSuchElementException elementException) + { + System.err.println("Invalid input. Please try again."); + input.nextLine(); // discard input so user can try again + } // end catch + + System.out.printf("%s %s\n%s", "Enter account number (>0),", + "first name, last name and balance.", "? "); + } // end while + } // end method addRecords + + // close file and terminate application + public void closeFile() + { + try // close file + { + if (output != null) + { + output.close(); + } // end try + } + catch (IOException ioException) + { + System.err.println("Error closing file."); + System.exit(1); + } // end catch + } // end method closeFile +} // end class CreateSequentialFile \ No newline at end of file diff --git a/17.5 Object Serialization/src/CreateSequentialFileTest.java b/17.5 Object Serialization/src/CreateSequentialFileTest.java new file mode 100644 index 0000000..3fff25b --- /dev/null +++ b/17.5 Object Serialization/src/CreateSequentialFileTest.java @@ -0,0 +1,14 @@ +// Fig. 17.17: CreateSequentialFileTest.java +// Testing class CreateSequentialFile. + +public class CreateSequentialFileTest +{ + public static void main(String[] args) + { + CreateSequentialFile application = new CreateSequentialFile(); + + application.openFile(); + application.addRecords(); + application.closeFile(); + } // end main +} // end class CreateSequentialFileTest \ No newline at end of file diff --git a/17.5 Object Serialization/src/ReadSequentialFile.java b/17.5 Object Serialization/src/ReadSequentialFile.java new file mode 100644 index 0000000..5448e16 --- /dev/null +++ b/17.5 Object Serialization/src/ReadSequentialFile.java @@ -0,0 +1,76 @@ +/** + * Created by P Trang on 8/18/2015. + * Fig. 17.18: ReadSequentialFile.java + * Reading a file of objects sequentially with ObjectInputStream + * and displaying each record + */ +import java.io.EOFException; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.ObjectInputStream; + +public class ReadSequentialFile +{ + private ObjectInputStream input; + + // enable user to select file to open + public void openFile() + { + try // open file + { + input = new ObjectInputStream(new FileInputStream("clients.ser")); + } // end try + catch (IOException ioException) + { + System.err.println("Error opening file."); + } // end catch + } // end method openFile + + // read record from file + public void readRecords() + { + AccountRecordSerializable record; + System.out.printf("%-10s%-12s%-12s%10s\n", "Account", + "First Name", "Last Name", "Balance"); + + try // input the values from the file + { + while (true) + { + record = (AccountRecordSerializable) input.readObject(); + + // display record contents + System.out.printf("%-10d%-12s%-12s%10.2f\n", + record.getAccount(), record.getFirstName(), + record.getLastName(), record.getBalance()); + } // end while + } // end try + catch (EOFException endOfFileException) + { + return; // end of file was reached + } + catch (ClassNotFoundException classNotFoundException) + { + System.err.println("Unable to create object."); + } // end catch + catch (IOException ioException) + { + System.err.println("Error during read from file."); + } // end catch + } // end method readRecords + + // close file and terminate application + public void closeFile() + { + try // close file and exit + { + if (input != null) + input.close(); + } // end try + catch(IOException ioException) + { + System.err.println("Error closing file."); + System.exit(1); + } // end catch + } // each method closeFile +} // end class ReadSequentialFile diff --git a/17.5 Object Serialization/src/ReadSequentialFileTest.java b/17.5 Object Serialization/src/ReadSequentialFileTest.java new file mode 100644 index 0000000..89695b6 --- /dev/null +++ b/17.5 Object Serialization/src/ReadSequentialFileTest.java @@ -0,0 +1,16 @@ +/** + * Fig. 17.19: ReadSequentialFileTest.java + * Testing class ReadSequentialFile. + */ + +public class ReadSequentialFileTest +{ + public static void main(String [] args) + { + ReadSequentialFile application = new ReadSequentialFile(); + + application.openFile(); + application.readRecords(); + application.closeFile(); + } // end main +} // end class ReadSequentialFileTest \ No newline at end of file diff --git a/17.5 Object Serialization/src/SequentialFile/AccountRecord.java b/17.5 Object Serialization/src/SequentialFile/AccountRecord.java new file mode 100644 index 0000000..aec1245 --- /dev/null +++ b/17.5 Object Serialization/src/SequentialFile/AccountRecord.java @@ -0,0 +1,77 @@ +package SequentialFile; + +/** + * Fig. 17.4: SequentialFile.AccountRecord.java + * SequentialFile.AccountRecord class maintains information for one account. + */ + +public class AccountRecord +{ + private int account; + private String firstName; + private String lastName; + private double balance; + + // no-argument constructor calls other constructor with default values + public AccountRecord() + { + this(0, "", "", 0.0); // call four-argument contsructor + } + + // initialize a record + public AccountRecord(int acct, String first, String last, double bal) + { + setAccount(acct); + setFirstName(first); + setLastName(last); + setBalance(bal); + } // end four-argument SequentialFile.AccountRecord constructor + + // set account number + public void setAccount(int acct) + { + account = acct; + } // end method setAccount + + // get account number + public int getAccount() + { + return account; + } // end method getAccount + + // set first name + public void setFirstName(String first) + { + firstName = first; + } // end method setFirstName + + // get first name + public String getFirstName() + { + return firstName; + } // end method getFirstName + + // set last name + public void setLastName(String last) + { + lastName = last; + } // end method setLastName + + // get last name + public String getLastName() + { + return lastName; + } // end method getLastName + + // set balance + public void setBalance(double bal) + { + balance = bal; + } // end method setBalance + + // get balance + public double getBalance() + { + return balance; + } // end method getBalance +} // end class SequentialFile.AccountRecord \ No newline at end of file diff --git a/17.5 Object Serialization/src/SequentialFile/CreateTextFile.java b/17.5 Object Serialization/src/SequentialFile/CreateTextFile.java new file mode 100644 index 0000000..7f4ebe9 --- /dev/null +++ b/17.5 Object Serialization/src/SequentialFile/CreateTextFile.java @@ -0,0 +1,99 @@ +package SequentialFile; /** + * Fig. 17.5: SequentialFile.CreateTextFile.java + * Writing data to a sequential text file with class Formatter. + */ + +import java.io.FileNotFoundException; +import java.util.Formatter; +import java.util.FormatterClosedException; +import java.util.NoSuchElementException; +import java.util.Scanner; + +public class CreateTextFile +{ + private Formatter output; // object used to output text to file + + // enable user to open file + public void openFile() + { + try + { + output = new Formatter("clients.txt"); // open the file + } // end try + catch (SecurityException securityException) + { + System.err.println( + "You do not have write access to this file."); + System.exit(1); // terminate the program + } // end catch + catch (FileNotFoundException fileNotFoundException) + { + System.err.println("Error opening or creating file."); + System.exit(1); // terminate the program + } // end catch + } // end method openFile + + // add records to file + public void addRecords() + { + // object to be written to file + AccountRecord record = new AccountRecord(); + Scanner input = new Scanner(System.in); + + System.out.printf("%s\n%s\n%s\n%s\n\n", + "To terminate input, type the ned-of-file indicator ", + "when you are prompted to enter input.", + "On UNIX/Linux/Mac OS X type d then press Enter", + "On Windows type z then press Enter"); + + System.out.printf("%s\n%s", + "Enter account number (> 0), first name, last name and balance.", + "? "); + + while (input.hasNext()) // loop until end-of-file indicator + { + try // output values to file + { + // retrieve data to be output + record.setAccount(input.nextInt()); + record.setFirstName(input.next()); + record.setLastName(input.next()); + record.setBalance(input.nextDouble()); + + if (record.getAccount() > 0) + { + // write new record + output.format("%d %s %s %.2f\n", record.getAccount(), + record.getFirstName(), record.getLastName(), + record.getBalance()); + } // end if + else + { + System.out.println( + "Account number must be greater than 0." + ); + } // end else + } // end try + catch (FormatterClosedException formatterClosedException) + { + System.err.println("Error writing to file."); + return; + } // end catch + catch (NoSuchElementException elementException) + { + System.err.println("Invalid input. Please Try again."); + input.nextLine(); // discard input so user can try again + } // end catch + + System.out.printf("%s %s\n%s", "Enter account number (>0),", + "first name, last nawe and balance.", "? "); + } // end while + } // end method addRecords + + // close file + public void closeFile() + { + if (output != null) + output.close(); + } // end method closeFile +} // end class SequentialFile.CreateTextFile \ No newline at end of file diff --git a/17.5 Object Serialization/src/SequentialFile/CreateTextFileTest.java b/17.5 Object Serialization/src/SequentialFile/CreateTextFileTest.java new file mode 100644 index 0000000..87ca4e4 --- /dev/null +++ b/17.5 Object Serialization/src/SequentialFile/CreateTextFileTest.java @@ -0,0 +1,13 @@ +package SequentialFile;// Testing the SequentialFile.CreateTextFile class + +public class CreateTextFileTest +{ + public static void main(String[] args) + { + CreateTextFile application = new CreateTextFile(); + + application.openFile(); + application.addRecords(); + application.closeFile(); + } // end main +} // diff --git a/17.5 Object Serialization/src/SequentialFile/ReadTextFile.java b/17.5 Object Serialization/src/SequentialFile/ReadTextFile.java new file mode 100644 index 0000000..6f25539 --- /dev/null +++ b/17.5 Object Serialization/src/SequentialFile/ReadTextFile.java @@ -0,0 +1,73 @@ +package SequentialFile; /** + * Fig. 17.9: SequentialFile.ReadTextFile.java + * This program reads a text files and displays each record. + */ + +import java.io.File; +import java.io.FileNotFoundException; +import java.util.NoSuchElementException; +import java.util.Scanner; + +public class ReadTextFile +{ + private Scanner input; + + // enable user to open file + public void openFile() + { + try + { + input = new Scanner(new File("clients.txt")); + } // end try + catch(FileNotFoundException fileNotFoundException) + { + System.err.println("Error opening file."); + System.exit(1); + } // end catch + } // end method openFile + + // read record from file + public void readRecords() + { + // object to be written to screen + AccountRecord record = new AccountRecord(); + + System.out.printf("%-10s%-12s%-12s%10s\n", "Account", + "First Name", "Last Name", "Balance"); + try // read records from files using Scanner object + { + while (input.hasNext()) + { + record.setAccount(input.nextInt()); // read account number + record.setFirstName(input.next()); // read first name + record.setLastName(input.next()); // read last name + record.setBalance(input.nextDouble()); // read balance + + // display record contents + System.out.printf("%-10d%-12s%-12s%10.2f\n", + record.getAccount(), record.getFirstName(), + record.getLastName(), record.getBalance()); + } // end while + } // end try + catch (NoSuchElementException elementException) + { + System.err.println("File improperly formed."); + input.close(); + System.exit(1); + } // end catch + catch (IllegalStateException stateException) + { + System.err.println("Error reading from file."); + System.exit(1); + } // end catch + } // end method readRecords + + // close files and terminate application + public void closeFile() + { + if (input != null) + { + input.close(); // close file + } + } // end method closeFile +} // end class SequentialFile.ReadTextFile diff --git a/17.5 Object Serialization/src/SequentialFile/ReadTextFileTest.java b/17.5 Object Serialization/src/SequentialFile/ReadTextFileTest.java new file mode 100644 index 0000000..de840d3 --- /dev/null +++ b/17.5 Object Serialization/src/SequentialFile/ReadTextFileTest.java @@ -0,0 +1,13 @@ +package SequentialFile;// Testing the SequentialFile.ReadTextFile class. + +public class ReadTextFileTest +{ + public static void main(String[] args) + { + ReadTextFile application = new ReadTextFile(); + + application.openFile(); + application.readRecords(); + application.closeFile(); + } // end main +} // end class ReadTexFileTest diff --git a/17.7 Opening Files with JFileChooser/17.7 Opening Files with JFileChooser.iml b/17.7 Opening Files with JFileChooser/17.7 Opening Files with JFileChooser.iml new file mode 100644 index 0000000..c90834f --- /dev/null +++ b/17.7 Opening Files with JFileChooser/17.7 Opening Files with JFileChooser.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/17.7 Opening Files with JFileChooser/src/FileDemonstration.java b/17.7 Opening Files with JFileChooser/src/FileDemonstration.java new file mode 100644 index 0000000..de916a1 --- /dev/null +++ b/17.7 Opening Files with JFileChooser/src/FileDemonstration.java @@ -0,0 +1,92 @@ +import javax.swing.*; +import java.awt.*; +import java.io.File; + +/** + * Created by P Trang on 8/23/2015. + */ +public class FileDemonstration extends JFrame +{ + private JTextArea outputArea; // used for output + private JScrollPane scrollPane; // used to provide scrolling to output + + // set up GUI + public FileDemonstration() + { + super( "Testing class File" ); + + outputArea = new JTextArea(); + + // add outputArea to scrollPane + scrollPane = new JScrollPane(outputArea); + + add(scrollPane, BorderLayout.CENTER); // add scrollPane to GUI + + setSize(400, 400); // set GUI size + setVisible(true); // display GUI + + analyzePath(); // create and analyze File object + } // end FileDemonstration constructor + + // allow user to specify file or directory name + private File getFileOrDirectory() + { + // display file dialog, so user can choose file or directory to open + JFileChooser fileChooser = new JFileChooser(); + fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); + int result = fileChooser.showOpenDialog(this); + + // if user clicked Cancel button on dialog, return + if (result == JFileChooser.CANCEL_OPTION) + System.exit(1); + + File fileName = fileChooser.getSelectedFile(); // get File + + // display error if invalid + if ((fileName == null) || (fileName.getName().equals(""))) + { + JOptionPane.showMessageDialog(this, "Invalid Name", + "Invalid Name", JOptionPane.ERROR_MESSAGE); + System.exit(1); + } // end if + + return fileName; + } // end method getFile + + // display information about file or directory user specifies + public void analyzePath() { + // create File object based on user input + File name = getFileOrDirectory(); + + if (name.exists()) // if name exists, output information about it. + { + // display file (or directory) information + outputArea.setText(String.format( + "%s%s\n%s\n%s\n%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s", + name.getName(), " exists", + (name.isFile() ? "is a file" : "is not a file"), + (name.isDirectory() ? "is a directory" : "is not a directory"), + (name.isAbsolute() ? "is absolute path" : "is not absolute path"), + "Last modified: ", name.lastModified(), + "Length: ", name.length(), + "Path: ", name.getPath(), + "Absolute path: ", name.getAbsolutePath(), + "Parent: ", name.getParent())); + + if (name.isDirectory()) // output directory listing + { + String[] directory = name.list(); + outputArea.append("\n\nDirectory contents:\n"); + + for (String directoryName : directory) + outputArea.append(directoryName + "\n"); + + } + } + else // not file or dircetory, output error message + { + JOptionPane.showMessageDialog(this, name + + "does not exst.", "ERROR", JOptionPane.ERROR_MESSAGE); + } + } +} diff --git a/17.7 Opening Files with JFileChooser/src/FileDemonstrationTest.java b/17.7 Opening Files with JFileChooser/src/FileDemonstrationTest.java new file mode 100644 index 0000000..b376680 --- /dev/null +++ b/17.7 Opening Files with JFileChooser/src/FileDemonstrationTest.java @@ -0,0 +1,13 @@ +import javax.swing.*; + +/** + * Created by P Trang on 8/24/2015. + */ +public class FileDemonstrationTest +{ + public static void main(String[] args) + { + FileDemonstration application = new FileDemonstration(); + application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + } +}