我正在编写一个使用两个数组列表的程序。我研究了如何将对象写为二进制,我试过实现它,但它从来没有正确工作。我需要能够运行程序,创建文件,然后写入文件,当我想保存。下一次加载程序时,它需要能够将数组列表读入。我已经在我存储的两个对象中实现了Serializable
import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;
//Add person functionality next
public class main {
ArrayList<Person> people = new ArrayList<Person>();
ArrayList<Date> dates = new ArrayList<Date>();
//Possibly add a checkExistence Function somewhere
//Otherwise self explanatory
public boolean newPerson(){
Scanner kbd = new Scanner(System.in);
String input = "";
boolean nameIsCorrect = false;
boolean typeIsCorrect = false;
do{
boolean nameContinue = false;
while(!nameContinue){
System.out.println("What is the name?");
input = kbd.nextLine();
nameContinue = yesOrNo();
if(nameContinue){
nameContinue = checkForExistence(input);
if(!nameContinue){
System.out.println("Name already exists, try again");
}
}
}
String[] tokens = input.split(" ");
if(tokens.length == 1){
String name = tokens[0];
String type = "";
do{
System.out.println("What type? F (Family) P (Punch) S (Season)");
input = kbd.nextLine();
if(input.equalsIgnoreCase("f")){
type = "f";
typeIsCorrect = true;
nameIsCorrect = true;
}
else if(input.equalsIgnoreCase("s")){
type = "s";
typeIsCorrect = true;
nameIsCorrect = true;
}
else if(input.equalsIgnoreCase("p")){
type = "p";
typeIsCorrect = true;
nameIsCorrect = true;
}
else{
System.out.println("Invalid, try again");
}
} while(!typeIsCorrect);
Person np = new Person(name, type);
people.add(np);
System.out.println(np.getName() + " added!");
}
else{
System.out.println("Not correct format let's try again");
}
} while(!nameIsCorrect);
return true;
}//End of newPerson function
//Cycles through and prints a roster
public boolean printPeopleList(){
for(int i = 0; i < people.size(); i++){
System.out.println(people.get(i).getName());
}
return true;
}
//Testing for valid input
public boolean testDateValidity(String input, int which){
if(which == 1){
String[] dates = new String[21];
int count = 0;
for(int i = 1; i <= 12; i++){
if(i < 10){
dates[count] = "0" + Integer.toString(i);
count++;
}
dates[count] = Integer.toString(i);
count++;
}
for(int j = 0; j < dates.length; j++){
if(input.equalsIgnoreCase(dates[j])){
return true;
}
}
}
else if(which == 2){
String[] dates = new String[40];
int count = 0;
for(int i = 1; i <= 31; i++){
if(i < 10){
dates[count] = "0" + Integer.toString(i);
count++;
}
dates[count] = Integer.toString(i);
count++;
}
for(int j = 0; j < dates.length; j++){
if(input.equalsIgnoreCase(dates[j])){
return true;
}
}
}
else{
return false;
}
return false;
}
//Cycles through and prints all dates and their attendance
public boolean printListOfDates(){
System.out.println("DatetPeople");
for(int i = 0; i < dates.size(); i++){
System.out.println(dates.get(i).toString());
}
return true;
}
public boolean printCurrentPeople(int day){
dates.get(day).printList();
return true;
}
//Returns the day position from the ArrayList
public int findDayPosition(String month, String day){
for(int i = 0; i < dates.size(); i++){
if(month.equalsIgnoreCase(dates.get(i).getMonth()) && day.equalsIgnoreCase(dates.get(i).getDay())){
return i;
}
}
return -1;
}
public boolean addVisit(String name, int date){
for(int i = 0; i < people.size(); i++){
if(people.get(i).getName().equalsIgnoreCase(name)){
people.get(i).incrementVisits();
people.get(i).addDay(dates.get(date).toStringPerson());
dates.get(date).addVisitor(name);
return true;
}
}
System.out.println("Person not found");
return false;
}
public boolean addVisit(String name, int visits, int date){
for(int i = 0; i < people.size(); i++){
if(people.get(i).getName().equalsIgnoreCase(name)){
people.get(i).incrementVisits(visits);
dates.get(date).addVisitor(name, visits);
people.get(i).addDay(dates.get(date).toStringPerson(), visits);
return true;
}
}
System.out.println("Person not found");
return false;
}
public boolean regAdd(int date){
dates.get(date).addRegular();
return true;
}
public boolean regAdd(int date, int visits){
dates.get(date).addRegular(visits);
return true;
}
public boolean helpFunction(){
File fin = new File("help.txt");
if(!fin.exists()){
System.out.println("I'm sorry the help file has become corrupted :(");
System.out.println("Please contact the maker of this program to fix it");
System.out.println("Upon contact he will probably let out a loud UGH");
}
else{
try{
FileReader fr = new FileReader(fin);
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine()) != null){
System.out.println(line);
}
} catch (FileNotFoundException fnf) {
//This line is completely pointless as the if function above serves its purpose
System.out.println("File was not found");
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
public boolean checkExistence(String name){
for(int i = 0; i < people.size(); i++){
if(people.get(i).getName().equalsIgnoreCase(name)){
return true;
}
}
return false;
}
public int getPersonPosition(String name){
for(int i = 0; i < people.size(); i++){
if(people.get(i).getName().equalsIgnoreCase(name)){
return i;
}
}
return -1;
}
public boolean printPersonDates(String name){
int x = getPersonPosition(name);
people.get(x).printDates();
return true;
}
public String changeMonth(){
Scanner kbd = new Scanner(System.in);
String input;
boolean continueProgram = false;
boolean monthContinue = false;
//Recieve the date
do{
System.out.println("What is the month?");
input = kbd.nextLine();
monthContinue = testDateValidity(input, 1);
if(monthContinue){
continueProgram = true;
}
} while (!continueProgram);
String month = input;
return month;
}
public String changeDay(){
Scanner kbd = new Scanner(System.in);
String input;
boolean continueProgram = false;
boolean dayContinue = false;
//Recieve the date
do{
System.out.println("What is the day?");
input = kbd.nextLine();
dayContinue = testDateValidity(input, 2);
if(dayContinue){
continueProgram = true;
}
} while (!continueProgram);
String day = input;
return day;
}
public boolean yesOrNo(){
Scanner kbd = new Scanner(System.in);
String input;
do{
System.out.println("Are you sure? Y or N");
input = kbd.nextLine();
} while(!checkYes(input));
if(input.equalsIgnoreCase("y") || input.equalsIgnoreCase("yes")){
return true;
}
else if(input.equalsIgnoreCase("n") || input.equalsIgnoreCase("no")){
return false;
}
else{
return false;
}
}
public boolean checkYes(String input){
if(input.equalsIgnoreCase("y") || input.equalsIgnoreCase("yes")){
return true;
}
else if(input.equalsIgnoreCase("n") || input.equalsIgnoreCase("no")){
return true;
}
else{
return false;
}
}
public boolean checkForExistence(String input){
for(int i = 0; i < people.size(); i++ ){
if(input.equalsIgnoreCase(people.get(i).getName())){
return false;
}
}
return true;
}
//Main Function
public static void main(String[] args){
main pool = new main();
Scanner kbd = new Scanner(System.in);
String input;
int numberData;
boolean continueProgram = false;
String month;
String day;
int dayPosition;
String dateString;
System.out.println("Welcome to the Pool Database Management System");
System.out.println("Copyright 2011 by Dalton Dick");
boolean monthContinue = false;
//Recieve the date
do{
System.out.println("What is the month?");
input = kbd.nextLine();
monthContinue = pool.testDateValidity(input, 1);
if(monthContinue){
continueProgram = true;
}
} while (!continueProgram);
month = input;
continueProgram = false;
boolean dayContinue = false;
//Recieve the date
do{
System.out.println("What is the day?");
input = kbd.nextLine();
dayContinue = pool.testDateValidity(input, 2);
if(dayContinue){
continueProgram = true;
}
} while (!continueProgram);
day = input;
//Adding the date object or finding the date already stored
if(pool.findDayPosition(month, day) != -1){
dayPosition = pool.findDayPosition(month, day);
System.out.println("Date already exists, using.");
}
else{
Date dayObject = new Date(month, day);
pool.dates.add(dayObject);
dayPosition = pool.findDayPosition(month, day);
System.out.println("Date added");
}
continueProgram = true;
boolean needsAFunction = true;
while(continueProgram){
System.out.println("Please enter a command");
input = kbd.nextLine();
String[] tokens = input.split(" ");
if(tokens[0].equalsIgnoreCase("help")){
if(tokens.length == 1){
pool.helpFunction();
}
else{
System.out.println("Invalid Command");
}
}
else if(tokens[0].equalsIgnoreCase("new")){
if(tokens.length == 1){
pool.newPerson();
}
else{
System.out.println("Invalid Command");
}
}
else if(tokens[0].equalsIgnoreCase("print")){
if(tokens.length == 2){
if(tokens[1].equalsIgnoreCase("people")){
pool.printPeopleList();
}
else if(tokens[1].equalsIgnoreCase("dates")){
pool.printListOfDates();
}
else if(tokens[1].equalsIgnoreCase("current")){
pool.printCurrentPeople(dayPosition);
}
}//End if Statement
else if(tokens.length == 3){
if(pool.checkExistence(tokens[1])){
if(tokens[2].equalsIgnoreCase("dates")){
pool.printPersonDates(tokens[1]);
}
else{
System.out.println("Invalid");
}
}
else{
System.out.println("Person does not exist");
}
}
}
else if(tokens[0].equalsIgnoreCase("quit") || tokens[0].equalsIgnoreCase("q") || tokens[0].equalsIgnoreCase("exit")){
System.out.println("Exiting System");
System.exit(0);
}
else if(tokens[0].equalsIgnoreCase("add")){
if(tokens.length == 1){
System.out.println("Invalid use of the command");
}
else if(tokens.length == 2){
pool.addVisit(tokens[1], dayPosition);
}
else if(tokens.length == 3){
try{
int x = Integer.parseInt(tokens[2]);
pool.addVisit(tokens[1], x, dayPosition);
} catch (NumberFormatException nfe){
System.out.println("Not a number");
}//End try catch block
}//End else if
}
else if(tokens[0].equalsIgnoreCase("change")){
if(tokens.length == 2){
if(tokens[1].equalsIgnoreCase("date")){
month = pool.changeMonth();
day = pool.changeDay();
if(pool.findDayPosition(month, day) != -1){
dayPosition = pool.findDayPosition(month, day);
System.out.println("Date already exists, using.");
}
else{
Date dayObject = new Date(month, day);
pool.dates.add(dayObject);
dayPosition = pool.findDayPosition(month, day);
System.out.println("Date added");
}
}
else{
System.out.println("Invalid Command");
}
}
else{
System.out.println("Invalid Command");
}
}
else if(tokens[0].equalsIgnoreCase("regular") || tokens[0].equalsIgnoreCase("reg")){
if(tokens.length == 1){
pool.regAdd(dayPosition);
}
else if(tokens.length == 2){
try{
pool.regAdd(dayPosition, Integer.parseInt(tokens[1]));
} catch (NumberFormatException nfe) {
System.out.println("Not correct input");
}
}
}
else{
System.out.println("Invalid Command");
}
}
}
}
检查这个例子:
ArrayList<Student> list = new ArrayList<Student>();
list.add(student1);
list.add(student2);
list.add(student3);
FileOutputStream fos;
try
{
fos = new FileOutputStream(FILENAME);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(list);
// read back
FileInputStream fis = new FileInputStream(FILENAME);
ObjectInputStream ois = new ObjectInputStream(fis);
Object obj = ois.readObject();
ArrayList<Student> listFromFile = (ArrayList) obj;
for (Student student: listFromFile)
{
System.out.println(student.toString());
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}