Image

Imagesugarplumkitty wrote in Imagejava_dev 😯confused

My file write doesn't write over existing data.

Thanks for all your help with my previous lab. Now I'm having a tough time figuring out why a file write doesn't write over the existing data, but adds all the records in my Vector into the front of the file.

I had been using File, FileOutputStream and DataOutputStream and switched to RandomAccessFile "rw" because I thought it was due to the file not being designated as "rw" but I'm still having the same problem. I keep deleting the file between runs because it grows so large. My functions work because my read through the Vector ends when the book title is found.

What am I doing wrong?

Thanks!



** the Library class **


import java.util.*;
import java.util.TimeZone.*;
import java.util.Calendar.*;
import java.util.GregorianCalendar.*;
import java.text.DateFormat;
import java.io.*;
import java.net.*;
import java.lang.Object.*;
import java.io.ObjectOutputStream.*;
import java.lang.String.*;

public class Library implements Serializable {

static Vector library = new Vector();
static Vector bookIdx = new Vector();
static FileInputStream myFile = null;
static ObjectOutputStream out = null;
static FileOutputStream outfilestream = null;
static DataOutputStream dataout = null;
static Calendar calendar;



public static boolean createBooks() {


library = new Vector();
library.add( new Book("Adventures of Huckleberry Finn", "Mark Twain" ) );
library.add( new Book("Chromosome 6", "Robin Cook") );
library.add( new Book("Core Java 2, Volume II--Advanced Features",
"Cay S. Horstmann") );
library.add( new Book("Gold Rush Tales of California",
"Janet Irene Atkinson") );
library.add( new Book("Great Expectations", "Charles Dickens") );
library.add( new Book("Hamlet", "William Shakespeare") );
library.add( new Book("Jane Eyre", "Charles Dickens") );
library.add( new Book("Midsummer Nights Dream", "William Shakespeare") );
library.add( new Book("Old Possum's Book of Practical Cats",
"T. S. Eliot") );
library.add( new Book("Othello", "William Shakespeare") );
library.add( new Book("Spoon River Anthology", "Edgar Lee Masters") );
library.add( new Book("Vicar of Wakefield", "Oliver Goldsmith") );
library.add( new Book("Wildflowers of California", "Susan Lamb") );


if( writeFile() )
return true;
else
return false;

} // end createBooks

public static String getDate( int addDays ) {
GregorianCalendar thisday = new GregorianCalendar();
Date d = thisday.getTime();
thisday.add(GregorianCalendar.DATE, addDays );
DateFormat df = DateFormat.getDateInstance();
String s = df.format(d);
return s;
}


public static void listBooks() {
String statusPrt;
Book book;

// iterate library
Iterator i = library.iterator();

while( i.hasNext() ) {
book = (Book) i.next();

if(book.getStatus() ) {
statusPrt = "available.";
}
else {
statusPrt = "checked out, due to return on " + book.getDueDate();
} // end else

System.out.println( book.getTitle() + " by " + book.getAuthor() +
" has been loaned " + book.getTimesLoaned() +
" time(s) and is " + statusPrt);
} // end while

} // end listBooks


public static void loanBook() {
boolean found = false;
boolean successful = false;
String request;
String title = "";
String author = "";
boolean status = false;
String dueDate = "";
int timesLoaned = 0;

request = corejava.Console.readLine(
"Type the title of a book you wish to borrow: " );


readFile();
synchronized(library) {
// iterate library
Iterator i = library.iterator();

while( i.hasNext() && !found) {
Book book = (Book) i.next();
title = (String) book.getTitle();
author = book.getAuthor();
status = book.getStatus();
dueDate = book.getDueDate();
timesLoaned = book.getTimesLoaned();

if( title.compareToIgnoreCase( request ) == 0 ) {

found = true;

if( book.getStatus() ) {
found = true;
successful = true;
book.setStatus( false );
dueDate = getDate(14);
// System.out.println(due );
book.setDueDate( dueDate );
book.setTimesLoaned( book.getTimesLoaned() + 1 );
break;

} // end if available
else
successful = false;
} // end if compare entry to title

} // end while


if( found ) {
if( successful ) {
System.out.println( "You have successfully checked out: " +
title + " by " + author );
System.out.println( "Please return it by " + dueDate );
writeFile();
}
else
System.out.println( "We're sorry. " +
title + " by " +
author +
" is not available. Please check back after " +
dueDate );
} // end if found
else
System.out.println( "We're sorry. You requested " + request +
" but we can't find that title. " +
" Please check your spelling and try again.");

} // end syncronized
return;
} // end loanbook


public static boolean returnBook() {

boolean found = false;
boolean successful = false;
String request;
String title = "";
String author = "";
boolean status = false;
String dueDate = "";
int timesLoaned = 0;

request = corejava.Console.readLine(
"Type the title of a book you wish to return: " );

readFile();
synchronized(library) {
// iterate library
Iterator i = library.iterator();

while( i.hasNext() && !found) {
Book book = (Book) i.next();
title = (String) book.getTitle();
author = book.getAuthor();
status = book.getStatus();
dueDate = book.getDueDate();
timesLoaned = book.getTimesLoaned();

if( title.compareToIgnoreCase( request ) == 0 ) {

found = true;

if( !book.getStatus() ) {
found = true;
successful = true;
book.setStatus( true );
break;

} // end if available
else
successful = false;
} // end if compare entry to title

} // end while


if( found ) {
if( successful ) {
System.out.println( "You have successfully returned: " +
title + " by " + author );
System.out.println( "Thank you." );
writeFile();
}
else
System.out.println( "Error. " +
title + " by " +
author +
" was not checked out.");
} // end if found
else
System.out.println( "We're sorry. You requested " + request +
" but we can't find that title. " +
" Please check your spelling and try again.");

} // end syncronized

return true;
} // end returnBook





public static String acceptRequest() {

String selection = "";

displayChoices();
selection = corejava.Console.readLine("Enter your Selection: " );
while( (selection.compareToIgnoreCase( "L" ) != 0) &&
(selection.compareToIgnoreCase( "R" ) != 0) &&
(selection.compareToIgnoreCase( "B" ) != 0) &&
(selection.compareToIgnoreCase( "Q" ) != 0) ) {
System.out.println( "" );
System.out.println( "Sorry, invalid choice. Valid choices are: " );
displayChoices();

selection = corejava.Console.readLine("Enter your Selection: " );
}

return selection;

} // end acceptRequest

public static void displayChoices() {
String Selection = "";

System.out.println( "" );
System.out.println( "Welcome to Linda's Library" );
System.out.println( "" );
System.out.println( "Type L to list all books" );
System.out.println( "Type R to return a book" );
System.out.println( "Type B to borrow a book" );
System.out.println( "Type Q to quit" );
System.out.println( "" );

} // end displayChoices


// these are copied from the SUN website and modified to compile.

private void writeObject(java.io.ObjectOutputStream out)
throws IOException, FileNotFoundException {}

private void readObject(java.io.ObjectInputStream in)
throws IOException, FileNotFoundException {}


public static boolean readFile() {
FileInputStream infilestream = null;
DataInputStream datain = null;

try {
RandomAccessFile f1 = new RandomAccessFile("C:\\Lab5Library.txt", "rw");
boolean eof = false;

if( f1.length() == 0 ) {
createBooks(); // file doesn't exist, create it.

}
else { // file exists, read it.

// the following was gleaned from:
// http://skywalker.cochise.edu/emeryj/cis208fileio.htm


while ( f1.length() > 0 ){

try {
String title = f1.readUTF();
String author = f1.readUTF();
boolean status = f1.readBoolean();
String dueDate = f1.readUTF();
int timesLoaned = f1.readInt();
library.add( new Book( title, author, status, dueDate, timesLoaned ) );
}
catch (IOException e) {
System.out.println("end of file");
break;

}

} // end while
} // end if/else

} catch (IOException e) {
System.out.println("Could not read file: " + e.toString());
System.out.println("creating the file");
createBooks();



try{
datain.close();
infilestream.close(); // close the stream
} catch (Exception e1){
e1.printStackTrace();

} finally{}

} // end catch
finally{};

return true;
} // end readFile



public static boolean writeFile() {

RandomAccessFile f1;

// iterate library
Iterator i = library.iterator();
try {

f1 = new RandomAccessFile("C:\\Lab5Library.txt", "rw");

f1.seek(0);

while( i.hasNext() ) {

try {
// the following file handling was gleaned from:
// http://skywalker.cochise.edu/emeryj/cis208fileio.htm

Book book = (Book) i.next();
f1.writeUTF( book.getTitle() );
f1.writeUTF( book.getAuthor() );
f1.writeBoolean( book.getStatus() );
f1.writeUTF( book.getDueDate() );
f1.writeInt( book.getTimesLoaned() );

}
catch(IOException e){
System.out.println(" couldn't write file ");
}

} // end while

try {
f1.close();
}
catch(IOException e){
System.out.println( "Couldn't close file " );
}
finally {};

return true;

} catch(IOException e){
System.out.println(" couldn't create file ");
return false;
}
} // end writeFile



public static void main(String[] args) throws ClassNotFoundException, IOException {


boolean keepGoing = true;
// get the supported ids for GMT-08:00 (Pacific Standard Time)
String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);
// if no ids were returned, something is wrong. get out.
if (ids.length == 0)
System.exit(0);

// create a Pacific Standard Time time zone
SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);

// set up rules for daylight savings time
pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);

// create a GregorianCalendar with the Pacific Daylight time zone
// and the current date and time

calendar = new GregorianCalendar(pdt);
Date date = new Date();
calendar.setTime(date);


readFile();
listBooks();
while( keepGoing ) {
String selection = acceptRequest();
if( selection.compareToIgnoreCase( "L" ) == 0 )
listBooks();
else if( selection.compareToIgnoreCase( "B" ) == 0 )
loanBook();
else if( selection.compareToIgnoreCase( "R" ) == 0 )
returnBook();
else if( selection.compareToIgnoreCase( "Q" ) == 0 )
keepGoing = false;
} // end while
} // end main
} // end class


** the Book class **

/**
* Program name: Book
* Programmer: Linda Montgomery
* Computer used: HP Pavilion with AMD Athlon XP-M CPU
* Description: Book information for a library. Includes
* methods to create, access and change some
* information about the books.
---------------------------------------------------------------
Book
---------------------------------------------------------------

---------------------------------------------------------------
+Book( title: String, author: String, dueDate: int, status: boolean, timesLoaned: int )
+Book( title: String, author: String, dueDate: int, status: boolean )
+Book( title: String, author: String, dueDate: int )
+Book( title: String, author: String )
+Book( title: String )
+Book( )
+getTitle( ) : String
+getAuthor( ) : String
+getDueDate( ) : int
+getStatus( ) : boolean
+getTimesLoaned( ) : int
+setDueDate( Date ) : int
+setStatus( status ) : boolean
+setTimesLoaned() : boolean
+toString() : String
----------------------------------------------------------------
*/
import java.util.*;
import java.lang.Object.*;
import java.io.*;
import java.util.GregorianCalendar.*;
import java.text.DateFormat.*;
import java.util.Calendar.*;

public class Book implements Serializable {
private String title;
private String author;
private boolean status;
private String dueDate;
private int timesLoaned;


public Book( String titleIn, String authorIn, boolean statusIn,
String dueDateIn, int timesLoanedIn ) {

title = titleIn;
author = authorIn;
status = statusIn;
dueDate = dueDateIn;
timesLoaned = timesLoanedIn;

} // end Book constructor


public Book( String titleIn, String authorIn, boolean statusIn,
String dueDateIn ) {
this( titleIn, authorIn, statusIn, dueDateIn, 0 );

} // end Book constructor



public Book( String titleIn, String authorIn, boolean statusIn ) {

this( titleIn, authorIn, statusIn, "January 1, 2005", 0 );

} // end Book constructor


public Book( String titleIn, String authorIn ) {
this( titleIn, authorIn, true, "January 1, 2005", 0 );

} // end Book constructor



public Book( String titleIn ) {

this( titleIn, "Anonymous", true, "January 1, 2005", 0 );

} // end Book constructor


public Book( ) {

this( "untitled", "Anonymous", true, "January 1, 2005", 0 );

} // end Book constructor




public String getTitle() {

return title;

} // end getTitle



public String getAuthor() {

return author;

} // end getAuthor


public boolean getStatus() {

return status;

} // end getStatus


public String getDueDate() {

return dueDate;

} // end getDueDate



public int getTimesLoaned() {

return timesLoaned;

} // end getTimesLoaned


public boolean setStatus( boolean newStatus ) {

status = newStatus;
return status;

} // end setStatus


public String setDueDate( String newDueDate ) {

dueDate = newDueDate;
return dueDate;

} // end setDueDate


public int setTimesLoaned( int newTimes ) {

timesLoaned = newTimes;
return timesLoaned;

} // end getTimesLoaned


public String toString( ) {

String string = ( this.getTitle() + this.getAuthor() + this.getStatus()
+ this.getDueDate() + this.getTimesLoaned() );
return string;


} // end toString method

} // end Book class