Files
G4G0-1/Semester 2/Programming 2/Project/Part 1/Library.java

81 lines
2.6 KiB
Java

/**
* Write a description of class Library here.
*
* @author (your name)
* @version (a version number or a date)
*/
// Import all required libraries. Not using .* as it is not good practice due to potential conflicts.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
import java.io.IOException;
import java.awt.FileDialog;
import java.awt.Frame;
public class Library
{
private ArrayList<LibraryItem> itemList; // Initialise an ArrayList of name itemList to store LibraryItems
/*
* Constructor for objects of class Library
*/
public Library()
{
itemList = new ArrayList<LibraryItem>();
}
/*
* Appends a LibraryItem to the itemList.
*/
public void storeItem( LibraryItem item )
{
itemList.add( item );
}
/*
* Prints to the terminal all items in the itemList
*/
public void printAllItems()
{
for( LibraryItem item : itemList )
{
item.printDetails();
}
}
public void readItemData() //throws IOException
{
try {
Frame frame = null; // Initialise a null frame
FileDialog fileBox = new FileDialog( frame, "Open", FileDialog.LOAD ); // Initialise filebox with the null frame pointer
fileBox.setVisible( true ); // Open a file selection dialog to the user.
Scanner fileScanner = new Scanner( new File( fileBox.getDirectory() + fileBox.getFile() ) );
while( fileScanner.hasNextLine() )
{
String lineItem = fileScanner.nextLine();
if ( !lineItem.contains( "//" ) && !lineItem.trim().isEmpty() ) { // Ensure no comments or empty lines are included
Scanner detailScanner = new Scanner ( lineItem ).useDelimiter(","); // Create a new scanner to grab the values in a comma separated list
LibraryItem libraryItem = new LibraryItem();
libraryItem.readData( detailScanner );
storeItem( libraryItem ); // Store the new LibraryItem in the itemList
}
}
}
catch( IOException e ) { // Catch any IO Exceptions that may occur from improper file selection.
System.err.println( "Caught IOException: " + e.getMessage() + "\nAn I/O Exception has occurred, please check file is readable and correct format." );
}
}
}