java - 在 Java 中写入二进制文件

标签 java binary arraylist

我正在制作一个使用两个数组列表的程序。我研究了如何将对象写入二进制文件,并尝试实现它,但它永远无法正常工作。我需要能够运行程序创建文件,然后在我想保存时写入文件。下次加载程序时,它需要能够读回数组列表。我已经在我存储的两个对象中实现了 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("Date\tPeople");
        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");
            }
        }
    }
}

最佳答案

检查 this示例:

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();           
}

关于java - 在 Java 中写入二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5645390/

相关文章:

java - 如何使用 java 日志记录将消息记录在单独的日志文件中?

java - 为什么下面的java代码会出错?

c - 为什么 0x1 被解释为小于 0xC0000000?

java - 在数组列表中查找索引总是出现在-1

java - 在链表末尾插入并不是一个特殊情况。那么数组的末尾呢?

java - 使用其他类的数组列表和适配器

java - 如何将第一个数字 (0) 映射为数组中的 Int?

java - 找不到此类元素错误

javascript - 有没有办法用 XMLHttpRequest 对象发送二进制数据?

file - Matlab:如何从文件中读取二进制数?