1. Create a file using any word-processing program or text editor. Write an application that displays the file’s name, containing folder, size, and time of last modification. Save the file as FileStatistics.java.

    import java.nio.file.*; import java.nio.file.attribute.*; import java.io.IOException; public class FileStatistics { public static void main(String[] args) { Path file = Paths.get("C:\\Java\\Chapter.13\\TestData.txt"); try { int count = file.getNameCount(); System.out.println("Path is " + file.toString()); System.out.println("File name is " + file.getFileName()); System.out.println("Folder name is " + file.getName(count - 2)); BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class); System.out.println("File's size is " + attr.size()); FileTime time = attr.creationTime(); System.out.println("File's creation time is " + time); } catch(IOException e) { System.out.println("IO Exception"); } } }
  2. Create three files of any type you choose—for example, word-processing documents, spreadsheets, or pictures. Write an application that determines whether the first two files are located in the same folder as the third one. Test the program when the files are in the same folder and when they are not. Save the file as CompareFolders.java.

    import java.nio.file.*; import java.io.IOException; public class CompareFolders { public static void main(String[] args) { Path file1 = Paths.get("C:\\Java\\Chapter.12\\TestData1.txt"); Path file2 = Paths.get("C:\\Java\\Chapter.13\\TestData2.txt"); Path file3 = Paths.get("C:\\Java\\Chapter.13\\TestData3.txt"); boolean foldersAreSame = true; try { int count1 = file1.getNameCount(); int count2 = file2.getNameCount(); int count3 = file3.getNameCount(); Path name3; System.out.println("Path for file1 is " + file1.toString()); System.out.println("Path for file2 is " + file2.toString()); System.out.println("Path for file3 is " + file3.toString()); for(int x = 0; x < count3 - 1; ++x) { name3 = file3.getName(x); if(!(file1.getName(x).equals(name3)) && file2.getName(x).equals(name3)) foldersAreSame = false; } if(foldersAreSame) System.out.println("All files are in the same folder"); else System.out.println("Files are not in the same folder"); } catch(Exception e) { System.out.println("IO Exception"); } } }
  3. Create a file that contains a line of your favorite song lyric. Use a text editor such as Notepad, and save the file. Copy the file contents, and paste them into a word-processing program such as Word. Write an application that displays the sizes of the two files as well as the ratio of their sizes to each other. Save the file as FileSizeComparison.java.

    import java.nio.file.*; import java.nio.file.attribute.*; import java.io.IOException; public class FileSizeComparison { public static void main(String[] args) { Path textFile = Paths.get("C:\\Java\\Chapter.13\\lyric.txt"); Path wordFile = Paths.get("C:\\Java\\Chapter.13\\lyric.docx"); try { BasicFileAttributes attrText = Files.readAttributes(textFile, BasicFileAttributes.class); BasicFileAttributes attrWord = Files.readAttributes(wordFile, BasicFileAttributes.class); long textSize = attrText.size(); long wordSize = attrWord.size(); double ratio = textSize * 100.0 / wordSize; System.out.println(textFile.toString() + " is " + textSize + " bytes long"); System.out.println(wordFile.toString() + " is " + wordSize + " bytes long"); System.out.println("The text file is " + ratio + "% of the size of the Word file"); } catch(IOException e) { System.out.println("IO Exception"); } } }
  4. Write an application that determines which, if any, of the following files are stored in the folder where you have saved the exercises created in this chapter: autoexec.bat, CompareFolders.java, FileStatistics.class, and Hello.doc. Save the file as FindSelectedFiles.java.

    import java.nio.file.*; import java.nio.file.attribute.*; import java.io.IOException; public class FindSelectedFiles { public static void main(String[] args) { Path f1 = Paths.get("C:\\Java\\autoexec.bat"); Path f2 = Paths.get("C:\\Java\\CompareFolders.java"); Path f3 = Paths.get("C:\\Java\\FileStatistics.class"); Path f4 = Paths.get("C:\\Java\\Hello.doc"); int count = 0; try { if(Files.exists(f1)) { System.out.println(f1.toString() + " exists"); ++count; } if(Files.exists(f2)) { System.out.println(f2.toString() + " exists"); ++count; } if(Files.exists(f3)) { System.out.println(f3.toString() + " exists"); ++count; } if(Files.exists(f4)) { System.out.println(f4.toString() + " exists"); ++count; } System.out.println(count + " of the files exist"); } catch(Exception e) { System.out.println("IO Exception"); } } }
    1. Create a program that allows a user to input customer records (ID number, first name, last name, and balance owed) and save each record to a file. Save the program as WriteCustomerList.java. When you execute the program, be sure to enter multiple records that have the same last name because you will search for repeated first names in part d of this exercise.

      import java.nio.file.*; import java.io.*; import static java.nio.file.AccessMode.*; import java.util.Scanner; public class WriteCustomerList { public static void main(String[] args) { Path file = Paths.get("C:\\Java\\Chapter.13\\CustomerList.txt"); Scanner kb = new Scanner(System.in); String[] array = new String[3]; String s = ""; String delimiter = ","; String id; String firstName; String lastName; double balance; final String QUIT = "ZZZ"; try { OutputStream output = new BufferedOutputStream(Files.newOutputStream(file)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output)); System.out.print("Enter ID number or " + QUIT + " to quit >> "); id = kb.nextLine(); while(!id.equals(QUIT)) { System.out.print("Enter first name >> "); firstName = kb.nextLine(); System.out.print("Enter last name >> "); lastName = kb.nextLine(); System.out.print("Enter balance >> "); balance = kb.nextDouble(); kb.nextLine(); s = id + delimiter + firstName + delimiter + lastName + delimiter + balance + System.getProperty("line.separator"); writer.write(s, 0, s.length()); System.out.print("Enter ID number or " + QUIT + " to quit >> "); id = kb.nextLine(); } writer.close(); } catch(Exception e) { System.out.println("Message: " + e); } } }
    2. Write an application that reads the file created by the WriteCustomerList application and displays the records. Save the file as DisplaySavedCustomerList.java.

      import java.nio.file.*; import java.io.*; import static java.nio.file.AccessMode.*; public class DisplaySavedCustomerList { public static void main(String[] args) { Path file = Paths.get("C:\\Java\\Chapter.13\\CustomerList.txt"); String[] array = new String[4]; String s = ""; String delimiter = ","; try { InputStream input = new BufferedInputStream(Files.newInputStream(file)); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); s = reader.readLine(); while(s != null) { array = s.split(delimiter); for(int x = 0; x < array.length; ++x) System.out.print(array[x] + " "); System.out.println(); s = reader.readLine(); } reader.close(); } catch(Exception e) { System.out.println("Message: " + e); } } }
    3. Write an application that allows you to enter any ID number, reads the customer data file created in Exercise 5a, and displays the data for the customer. Display an appropriate message if the ID number cannot be found in the input file. Save the file as DisplaySelectedCustomer.java.

      import java.nio.file.*; import java.io.*; import static java.nio.file.AccessMode.*; import java.util.Scanner; public class DisplaySelectedCustomer { public static void main(String[] args) { Scanner keyBoard = new Scanner(System.in); Path file = Paths.get("C:\\Java\\Chapter.13\\CustomerList.txt"); String[] array = new String[4]; String s = ""; String delimiter = ","; String searchID; boolean wasFound = false; try { InputStream input = new BufferedInputStream(Files.newInputStream(file)); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); System.out.println(); System.out.print("Enter ID number to search for >> "); searchID = keyBoard.nextLine(); s = reader.readLine(); while(s != null) { array = s.split(delimiter); if(searchID.equals(array[0])) { wasFound = true; for(int x = 0; x < array.length; ++x) System.out.print(array[x] + " "); System.out.println(); } s = reader.readLine(); } if(!wasFound) System.out.println("No records found for " + searchID); reader.close(); } catch(Exception e) { System.out.println("Message: " + e); } } }
    4. Write an application that allows you to enter any last name and displays all the data for customers with the given last name. Display an appropriate message if the name cannot be found in the input file. Save the file as DisplaySelectedCustomersByName.java.

      import java.nio.file.*; import java.io.*; import static java.nio.file.AccessMode.*; import java.util.Scanner; public class DisplaySelectedCustomersByName { public static void main(String[] args) { Scanner keyBoard = new Scanner(System.in); Path file = Paths.get("C:\\Java\\Chapter.13\\CustomerList.txt"); String[] array = new String[4]; String s = ""; String delimiter = ","; String searchName; boolean wasFound = false; final int LAST_NAME_POSITION = 2; try { InputStream input = new BufferedInputStream(Files.newInputStream(file)); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); System.out.println(); System.out.print("Enter last name to search for >> "); searchName = keyBoard.nextLine(); s = reader.readLine(); while(s != null) { array = s.split(delimiter); if(searchName.equals(array[LAST_NAME_POSITION])) { wasFound = true; for(int x = 0; x < array.length; ++x) System.out.print(array[x] + " "); System.out.println(); } s = reader.readLine(); } if(!wasFound) System.out.println("No records found for " + searchName); reader.close(); } catch(Exception e) { System.out.println("Message: " + e); } } }
    5. Write an application that allows you to enter any purchase amount and displays all the data for customers with balances greater than the entered value. Display an appropriate message if no customers meet the criteria. Save the file as DisplaySelectedCustomersByBalance.java.

      import java.nio.file.*; import java.io.*; import static java.nio.file.AccessMode.*; import java.util.Scanner; public class DisplaySelectedCustomersByBalance { public static void main(String[] args) { Scanner keyBoard = new Scanner(System.in); Path file = Paths.get("C:\\Java\\Chapter.13\\CustomerList.txt"); String[] array = new String[4]; String s = ""; String delimiter = ","; double balance; double custBal; boolean wasFound = false; final int BAL_POSITION = 3; try { InputStream input = new BufferedInputStream(Files.newInputStream(file)); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); System.out.println(); System.out.print("Enter minimum balance >> "); balance = keyBoard.nextDouble(); s = reader.readLine(); while(s != null) { array = s.split(delimiter); custBal = Double.parseDouble(array[BAL_POSITION]); if(custBal >= balance) { wasFound = true; for(int x = 0; x < array.length; ++x) System.out.print(array[x] + " "); System.out.println(); } s = reader.readLine(); } if(!wasFound) System.out.println("No records found with a balance of at least $" + balance); reader.close(); } catch(Exception e) { System.out.println("Message: " + e); } } }
  5. Using a text editor, create a file that contains a list of at least 15 six-digit account numbers. Read in each account number and display whether it is valid. An account number is valid only if the last digit is equal to the remainder when the sum of the first five digits is divided by 10. For example, the number 223355 is valid because the sum of the first five digits is 15, the remainder when 15 is divided by 10 is 5, and the last digit is 5. Write only valid account numbers to an output file, each on its own line. Save the application as ValidateCheckDigits.java.

    import java.nio.file.*; import java.io.*; import java.nio.channels.FileChannel; import java.nio.ByteBuffer; import static java.nio.file.StandardOpenOption.*; public class ValidateCheckDigits { public static void main(String[] args) { Path fileIn = Paths.get("C:\\Java\\Chapter.13\\AcctNumsIn.txt"); Path fileOut = Paths.get("C:\\Java\\Chapter.13\\AcctNumsOut.txt"); String acct; int acctNum; int lastDigit; int digit; int sum; int x; String newline = "\n"; InputStream input = null; OutputStream output = null; try { input = Files.newInputStream(fileIn); BufferedReader reader = new BufferedReader (new InputStreamReader(input)); output = Files.newOutputStream(fileOut); acct = reader.readLine(); while(acct != null) { sum = 0; acctNum = Integer.parseInt(acct); lastDigit = acctNum % 10; acctNum = acctNum / 10; for(x = 0; x < 6; x++) { digit = acctNum % 10; acctNum = acctNum / 10; sum = sum + digit; } sum = sum % 10; if(sum == lastDigit) { System.out.println(acct + " is valid"); acct = acct + System.getProperty("line.separator"); byte[] data = acct.getBytes(); output.write(data); } else { System.out.println(acct + " is invalid"); } acct = reader.readLine(); } input.close(); output.close(); } catch (IOException e) { System.out.println(e); } } }
    1. Write an application that allows a user to enter a filename and an integer representing a file position. Assume that the file is in the same folder as your executing program. Access the requested position within the file, and display the next 10 characters there. Save the file as SeekPosition.java.

      import java.nio.file.*; import java.io.*; import java.nio.channels.FileChannel; import java.nio.ByteBuffer; import static java.nio.file.StandardOpenOption.*; import java.util.Scanner; public class SeekPosition { public static void main(String[] args) { String name; Scanner keyboard = new Scanner(System.in); int pos; final int SIZE = 10; System.out.print("Enter a file name >> "); name = keyboard.nextLine(); Path inputPath = Paths.get(name); Path fullPath = inputPath.toAbsolutePath(); System.out.print("Enter a position number >> "); pos = keyboard.nextInt(); byte[] data = new byte[SIZE]; ByteBuffer buffer = ByteBuffer.allocate(SIZE); FileChannel fc = null; String s; try { fc = (FileChannel)Files.newByteChannel(fullPath, READ); buffer= ByteBuffer.wrap(data); fc.position(pos); fc.read(buffer); s = new String(data); System.out.println(s); } catch (Exception e) { System.out.println("Error message: " + e); } } }
    2. Modify the SeekPosition application so that instead of displaying 10 characters, the user enters the number of characters to display, beginning with the requested position. Save the file as SeekPosition2.java.

      import java.nio.file.*; import java.io.*; import java.nio.channels.FileChannel; import java.nio.ByteBuffer; import static java.nio.file.StandardOpenOption.*; import java.util.Scanner; public class SeekPosition2 { public static void main(String[] args) { String name; Scanner keyboard = new Scanner(System.in); int pos; int numToDisplay; System.out.print("Enter a file name >> "); name = keyboard.nextLine(); Path inputPath = Paths.get(name); Path fullPath = inputPath.toAbsolutePath(); System.out.print("Enter a position number >> "); pos = keyboard.nextInt(); System.out.print("Enter number of characters to display >> "); numToDisplay = keyboard.nextInt(); byte[] data = new byte[numToDisplay]; ByteBuffer buffer = ByteBuffer.allocate(numToDisplay); FileChannel fc = null; String s; try { fc = (FileChannel)Files.newByteChannel(fullPath, READ); buffer= ByteBuffer.wrap(data); fc.position(pos); fc.read(buffer); s = new String(data); System.out.println(s); } catch (Exception e) { System.out.println("Error message: " + e); } } }
    1. Create an application that allows you to enter student data that consists of an ID number, first name, last name, and grade point average. Depending on whether the student’s grade point average is at least 2.0, output each record either to a file of students in good standing or those on academic probation. Save the program as StudentsStanding.java.

      import java.nio.file.*; import java.io.*; import static java.nio.file.StandardOpenOption.*; import java.util.Scanner; import java.nio.channels.FileChannel; public class StudentsStanding { public static void main(String[] args) { Scanner kb = new Scanner(System.in); Path goodFile = Paths.get("C:\\Java\\Chapter.13\\StudentsGoodStanding.txt"); Path probFile = Paths.get("C:\\Java\\Chapter.13\\StudentsAcademicProbation.txt"); String s = ""; String delimiter = ","; String stringId; String firstName; String lastName; double gpa; final String QUIT = "ZZZ"; final double CUTOFF = 2.0; try { OutputStream goodStream = new BufferedOutputStream(Files.newOutputStream(goodFile, CREATE)); BufferedWriter goodWriter = new BufferedWriter(new OutputStreamWriter(goodStream)); OutputStream probStream = new BufferedOutputStream(Files.newOutputStream(probFile, CREATE)); BufferedWriter probWriter = new BufferedWriter(new OutputStreamWriter(probStream)); System.out.print("Enter student ID >> "); stringId = kb.nextLine(); while(!stringId.equals(QUIT)) { System.out.print("Enter firstName >> "); firstName = kb.nextLine(); System.out.print("Enter last name >> "); lastName = kb.nextLine(); System.out.print("Enter grade point average >> "); gpa = kb.nextDouble(); kb.nextLine(); s = stringId + delimiter + firstName + delimiter + lastName + delimiter + gpa + System.getProperty("line.separator"); if(gpa < CUTOFF) probWriter.write(s, 0, s.length()); else goodWriter.write(s, 0, s.length()); System.out.print("Enter next student ID or " + QUIT + " to quit >> "); stringId = kb.nextLine(); } probWriter.close(); goodWriter.close(); } catch(Exception e) { System.out.println("Message: " + e); } } }
    2. Create an application that displays each record in the two files created in the StudentsStanding application in Exercise 8a. Display a heading to introduce the list produced from each file. For each record, display the ID number, first name, last name, grade point average, and the amount by which the grade point average exceeds or falls short of the 2.0 cutoff. Save the program as StudentsStanding2.java.

      import java.nio.file.*; import java.io.*; import static java.nio.file.StandardOpenOption.*; public class StudentsStanding2 { public static void main(String[] args) { Path goodFile = Paths.get("C:\\Java\\Chapter.13\\StudentsGoodStanding.txt"); Path probFile = Paths.get("C:\\Java\\Chapter.13\\StudentsAcademicProbation.txt"); String s = ""; try { InputStream goodStream = new BufferedInputStream(Files.newInputStream(goodFile)); BufferedReader goodReader = new BufferedReader(new InputStreamReader(goodStream)); InputStream probStream = new BufferedInputStream(Files.newInputStream(probFile)); BufferedReader probReader = new BufferedReader(new InputStreamReader(probStream)); System.out.println("\nProbationary Standing\n"); s = probReader.readLine(); while( s != null) { display(s); s = probReader.readLine(); } System.out.println("\nGood Standing\n"); s = goodReader.readLine(); while( s != null) { display(s); s = goodReader.readLine(); } probStream.close(); goodStream.close(); } catch(Exception e) { System.out.println("Message: " + e); } } public static void display(String s) { String[] array = new String[4]; String delimiter = ","; String stringId; String firstName; String lastName; double gpa; double overUnder; final double CUTOFF = 2.0; array = s.split(delimiter); stringId = array[0]; firstName = array[1]; lastName = array[2]; gpa = Double.parseDouble(array[3]); overUnder = gpa - CUTOFF; System.out.println("ID #" + stringId + " " + firstName + " " + lastName + " GPA: " + gpa + " " + overUnder + " from " + CUTOFF + " cutoff"); } }
    1. The Rochester Bank maintains customer records in a random access file. Write an application that creates 10,000 blank records and then allows the user to enter customer account information, including an account number that is 9998 or less, a last name, and a balance. Insert each new record into a data file at a location that is equal to the account number. Assume that the user will not enter invalid account numbers. Force each name to eight characters, padding it with spaces or truncating it if necessary. Also assume that the user will not enter a bank balance greater than 99,000.00. Save the file as CreateBankFile.java.

      import java.nio.file.*; import java.io.*; import java.nio.channels.FileChannel; import java.nio.ByteBuffer; import static java.nio.file.StandardOpenOption.*; import java.util.Scanner; import java.text.*; public class CreateBankFile { public static void main(String[] args) { Scanner input = new Scanner(System.in); Path file = Paths.get("C:\\Java\\Chapter.13\\BankAccounts.txt"); String s = "0000, ,00000.00" + System.getProperty("line.separator"); final int RECSIZE = s.length(); FileChannel fc = null; final int NUMRECS = 10000; long pos; String delimiter = ","; String idString; int id; String name; double balance; final String QUIT = "9999"; try { OutputStream output = new BufferedOutputStream(Files.newOutputStream(file, CREATE)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output)); for(int count = 0; count < NUMRECS; ++count) writer.write(s, 0, s.length()); writer.close(); } catch(Exception e) { System.out.println("Error message: " + e); } try { fc = (FileChannel)Files.newByteChannel(file, CREATE, WRITE); System.out.print("Enter 4-digit customer account number less than " + QUIT + " >> "); idString = input.nextLine(); while(!(idString.equals(QUIT))) { id = Integer.parseInt(idString); System.out.print("Enter name for customer >> "); name = input.nextLine(); StringBuilder sb = new StringBuilder(name); sb.setLength(8); name = sb.toString(); System.out.print("Enter balance >> "); balance = input.nextDouble(); input.nextLine(); DecimalFormat df = new DecimalFormat("00000.00"); s = idString + delimiter + name + delimiter + df.format(balance) + System.getProperty("line.separator"); byte data[] = s.getBytes(); ByteBuffer buffer = ByteBuffer.wrap(data); fc.position(id * RECSIZE); fc.write(buffer); System.out.print("Enter next customer account number or " + QUIT + " to quit >> "); idString = input.nextLine(); } fc.close(); } catch (Exception e) { System.out.println("Error message: " + e); } } }
    2. Create an application that uses the file created by the user in Exercise 9a and displays all existing accounts in account-number order. Save the file as ReadBankAccountsSequentially.java

      import java.nio.file.*; import java.io.*; import static java.nio.file.AccessMode.*; public class ReadBankAccountsSequentially { public static void main(String[] args) { Path file = Paths.get("C:\\Java\\Chapter.13\\BankAccounts.txt"); String[] array = new String[3]; String s = ""; String delimiter = ","; int id; String stringId; String name; double balance; try { InputStream input = new BufferedInputStream(Files.newInputStream(file)); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); System.out.println(); s = reader.readLine(); while(s != null) { array = s.split(delimiter); stringId = array[0]; id = Integer.parseInt(array[0]); if(id != 0) { name = array[1]; balance = Double.parseDouble(array[2]); System.out.println("ID#" + stringId + " " + name + " $" + balance); } s = reader.readLine(); } reader.close(); } catch(Exception e) { System.out.println("Message: " + e); } } }
    3. Create an application that uses the file created by the user in Exercise 9a and allows the user to enter an account number to view the account balance. Allow the user to view additional account balances until entering an application-terminating value of 9999. Save the file as ReadBankAccountsRandomly.java.

      import java.nio.file.*; import java.io.*; import java.nio.channels.FileChannel; import java.nio.ByteBuffer; import static java.nio.file.StandardOpenOption.*; import java.util.Scanner; import java.net.*; public class ReadBankAccountsRandomly { public static void main(String[] args) { Scanner keyBoard = new Scanner(System.in); Path file = Paths.get("C:\\Java\\Chapter.13\\BankAccounts.txt"); String s = "0000, ,00000.00" + System.getProperty("line.separator"); final int RECSIZE = s.length(); byte data[] = s.getBytes(); ByteBuffer buffer = ByteBuffer.wrap(data); FileChannel fc = null; String delimiter = ","; String idString; int id; String name; double balance; final String QUIT = "9999"; try { fc = (FileChannel)Files.newByteChannel(file, READ, WRITE); System.out.print("Enter account number >> "); idString = keyBoard.nextLine(); while(!idString.equals(QUIT)) { id = Integer.parseInt(idString); fc.position(id * RECSIZE); fc.read(buffer); buffer= ByteBuffer.wrap(data); s = new String(data); System.out.println("ID #" + id + " " + s); System.out.print("Enter next account number or " + QUIT + " to quit >> "); idString = keyBoard.nextLine(); } fc.close(); } catch (Exception e) { System.out.println("Error message: " + e); } } }
    1. Write a program that allows you to create a file of customers for a company. The first part of the program should create an empty file suitable for writing a three-digit ID number, six-character last name, and five-digit zip code for each customer. The second half of the program accepts user input to populate the file. For this exercise, assume that the user will correctly enter ID numbers and zip codes, but force the customer name to seven characters if it is too long or too short. Issue an error message, and do not save the records if the user tries to save a record with an ID number that already has been used. Save the program as CreateCustomerFile.java.

      import java.nio.file.*; import java.io.*; import java.nio.ByteBuffer; import static java.nio.file.StandardOpenOption.*; import java.util.Scanner; import java.nio.channels.FileChannel; public class CreateCustomerFile { public static void main(String[] args) { Scanner input = new Scanner(System.in); Path file = Paths.get("C:\\Java\\Chapter.13\\Customers.txt"); String s = "000, ,00000" + System.getProperty("line.separator"); String delimiter = ","; String[] array = new String[3]; byte data[] = s.getBytes(); ByteBuffer buffer = ByteBuffer.wrap(data); FileChannel fc = null; final int RECSIZE = s.length(); final int NUMRECS = 1000; final String QUIT = "999"; String custString; int custNum; String name; String zipCode; String fileNum; try { OutputStream output = new BufferedOutputStream(Files.newOutputStream(file, CREATE)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output)); for(int count = 0; count < NUMRECS; ++count) writer.write(s, 0, s.length()); writer.close(); } catch(Exception e) { System.out.println("Error message: " + e); } try { fc = (FileChannel)Files.newByteChannel(file, READ, WRITE); System.out.print("Enter customer number or " + QUIT + " to quit >> "); custString = input.nextLine(); while(!(custString.equals(QUIT))) { custNum = Integer.parseInt(custString); buffer = ByteBuffer.wrap(data); fc.position(custNum * RECSIZE); fc.read(buffer); s = new String(data); array = s.split(delimiter); fileNum = array[0]; if(!(fileNum.equals("000"))) System.out.println("Sorry - customer " + custString + " already exists"); else { System.out.print("Enter name for customer #" + custNum + " >> "); name = input.nextLine(); StringBuilder sb = new StringBuilder(name); sb.append(" "); sb.setLength(6); name = sb.toString(); System.out.print("Enter zip code >> "); zipCode = input.nextLine(); s = custString + delimiter + name + delimiter + zipCode + System.getProperty("line.separator"); data = s.getBytes(); buffer = ByteBuffer.wrap(data); fc.position(custNum * RECSIZE); fc.write(buffer); } System.out.print("Enter next customer number or " + QUIT + " to quit >> "); custString = input.nextLine(); } fc.close(); } catch (Exception e) { System.out.println("Error message: " + e); } } }
    2. Write a program that creates a file of items carried by the company. Include a three-digit item number and up to a 20-character description for each item. Issue an error message if the user tries to store an item number that already has been used. Save the program as CreateItemFile.java.

      import java.nio.file.*; import java.io.*; import java.nio.ByteBuffer; import static java.nio.file.StandardOpenOption.*; import java.util.Scanner; import java.nio.channels.FileChannel; public class CreateItemFile { public static void main(String[] args) { Scanner input = new Scanner(System.in); Path file = Paths.get("C:\\Java\\Chapter.13\\Items.txt"); String dummyItem = " "; String s = "000," + dummyItem + System.getProperty("line.separator"); String delimiter = ","; String[] array = new String[3]; byte data[] = s.getBytes(); ByteBuffer buffer = ByteBuffer.wrap(data); FileChannel fc = null; final int RECSIZE = s.length(); final int NUMRECS = 1000; final String QUIT = "999"; String itemString; int itemNum; String description; String fileNum; try { OutputStream output = new BufferedOutputStream(Files.newOutputStream(file, CREATE)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output)); for(int count = 0; count < NUMRECS; ++count) writer.write(s, 0, s.length()); writer.close(); } catch(Exception e) { System.out.println("Error message: " + e); } try { fc = (FileChannel)Files.newByteChannel(file, READ, WRITE); System.out.print("Enter item number or " + QUIT + " to quit >> "); itemString = input.nextLine(); while(!(itemString.equals(QUIT))) { itemNum = Integer.parseInt(itemString); buffer = ByteBuffer.wrap(data); fc.position(itemNum * RECSIZE); fc.read(buffer); s = new String(data); array = s.split(delimiter); fileNum = array[0]; if(!(fileNum.equals("000"))) System.out.println("Sorry - item " + itemString + " already exists"); else { System.out.print("Enter description for item #" + itemNum + " >> "); description = input.nextLine(); StringBuilder sb = new StringBuilder(description); sb.append(dummyItem); sb.setLength(dummyItem.length()); description = sb.toString(); s = itemString + delimiter + description + System.getProperty("line.separator"); data = s.getBytes(); buffer = ByteBuffer.wrap(data); fc.position(itemNum * RECSIZE); fc.write(buffer); } System.out.print("Enter next item number or " + QUIT + " to quit >> "); itemString = input.nextLine(); } fc.close(); } catch (Exception e) { System.out.println("Error message: " + e); } } }
    3. Write an application that takes customer orders. Allow a user to enter a customer number and item ordered. Display an error message if the customer number does not exist in the customer file or the item does not exist in the item file; otherwise, display all the customer information and item information. Save the program as CustomerItemOrder.java.

      import java.nio.file.*; import java.io.*; import java.nio.channels.FileChannel; import java.nio.ByteBuffer; import static java.nio.file.StandardOpenOption.*; import java.util.Scanner; public class CustomerItemOrder { public static void main(String[] args) { Scanner keyBoard = new Scanner(System.in); Path customers = Paths.get("C:\\Java\\Chapter.13\\Customers.txt"); Path items = Paths.get("C:\\Java\\Chapter.13\\Items.txt"); String customersString = "000, ,00000" + System.getProperty("line.separator"); final int CUSTOMERS_RECSIZE = customersString.length(); String itemsString = "000, " + System.getProperty("line.separator"); final int ITEMS_RECSIZE = itemsString.length(); byte[] dataCustomers = customersString.getBytes(); byte[] dataItems = itemsString.getBytes(); ByteBuffer bufferC = ByteBuffer.wrap(dataCustomers); ByteBuffer bufferI = ByteBuffer.wrap(dataItems); FileChannel fcCustomers = null; FileChannel fcItems = null; String[] arrayC = new String[3]; String[] arrayI = new String[2]; String cString; String iString; int cust; int item; String delimiter = ","; final String QUIT = "999"; try { fcCustomers = (FileChannel)Files.newByteChannel(customers, READ); fcItems = (FileChannel)Files.newByteChannel(items, READ); System.out.print("Enter customer number number or " + QUIT + " to quit >> "); cString = keyBoard.nextLine(); while(!cString.equals(QUIT)) { cust = Integer.parseInt(cString); fcCustomers.position(cust * CUSTOMERS_RECSIZE); fcCustomers.read(bufferC); bufferC= ByteBuffer.wrap(dataCustomers); customersString = new String(dataCustomers); arrayC = customersString.split(delimiter); if(arrayC[0].equals("000")) System.out.println("No customer " + cString + " found"); else { System.out.print("Enter item number >> "); iString = keyBoard.nextLine(); item = Integer.parseInt(iString); bufferI= ByteBuffer.wrap(dataItems); fcItems.position(item * ITEMS_RECSIZE); fcItems.read(bufferI); itemsString = new String(dataItems); arrayI = itemsString.split(delimiter); if(arrayI[0].equals("000")) System.out.println("No such item " + iString + " found"); else { System.out.print("Customer: " + arrayC[0] + " Name: " + arrayC[1] + " zip code: " + arrayC[2]); System.out.println(" ordered Item #" + arrayI[0] + " which is a " + arrayI[1]); } } System.out.print("Enter customer ID number or " + QUIT + " to quit >> "); cString = keyBoard.nextLine(); } fcCustomers.close(); fcItems.close(); } catch (Exception e) { System.out.println("Error message: " + e); } } }