I am writing a simple database class and it works fine the first time but then i get this error message the times after. If i delete the text file that it is writing to then it is fine. Please help I am lost at this point.
import java.io.*;
import java.util.Scanner;
public class Database {
private String filename;
private File file;
private int numberEntries;
public Database(String name) throws IOException{
numberEntries = 0;
filename = name;
file = new File(name);
if (!file.exists()){
file.createNewFile();
}
else{
Scanner scan = new Scanner(new FileInputStream(file));
while(scan.hasNext()) {
scan.nextLine();
numberEntries ++;
}
}
}
public String getDatabaseName(){
return filename;
}
public void setDatabaseName(String newName) throws IOException{
filename = newName;
File tempFile = new File(newName);
if(!tempFile.exists()){
tempFile.createNewFile();
}
file = tempFile;
}
public int getNumEntries(){
return numberEntries;
}
public void setNumEntries(int newNumEntries){
numberEntries = newNumEntries;
}
public void addEntry(Entry E){
PrintWriter pw = null;
try {
pw = new PrintWriter(new FileOutputStream(file, true));
}
catch(FileNotFoundException e){
System.out.println("Could not open file");
}
pw.println(E);
pw.close();
numberEntries ++;
}
public Entry[] fileToArray() throws IOException{
Entry[] entryArray = new Entry[this.getNumEntries()];
Scanner scan = null;
try{
scan = new Scanner(new FileInputStream(file));
}
catch(FileNotFoundException e){
System.out.println("Could not open file.");
}
scan.useDelimiter(" , |\n");
for (int i = 0; i < this.getNumEntries(); i++){
entryArray[i] = new Entry(scan.next(),scan.next(),scan.next());
}
return entryArray;
}
public void deleteEntry(Entry toBeDeleted) throws IOException{
Entry[] fileArray = this.fileToArray();
PrintWriter pw = null;
try {
pw = new PrintWriter(new FileOutputStream(file));
}
catch(FileNotFoundException e){
System.out.println("Could not open file");
}
for (int i = 0; i < fileArray.length; i++){
if (!fileArray[i].equals(toBeDeleted)){
pw.println(fileArray[i]);
}
}
pw.close();
}
public static void main(String[] args) throws IOException{
Entry entry = new Entry("Toy Story 3", "2010", "G");
Entry e1 = new Entry("The Matrix", "1999","R");
Database database = new Database("database.txt");
database.addEntry(entry);
database.addEntry(e1);
Entry[] a = database.fileToArray();
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
Entry delete = new Entry("*", "*", "*");
database.deleteEntry(delete);
}
}