我不明白我不断得到的这个InvocationTargetException的原因

时间:2019-06-23 10:42:35

标签: java javafx invocationtargetexception

所以我有一个Javafx应用程序,它运行良好,但是当我在FXML控制器文件中添加新的控制器方法时,此错误不断出现!

Executing C:\Users\Mohsen\Documents\NetBeansProjects\TestPTFX2\dist\run1797453756\TestPTFX2.jar using platform C:\Program Files\Java\jdk1.8.0_45\jre/bin/java
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1770)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1653)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Node.fireEvent(Node.java:8390)
    at javafx.scene.control.Button.fire(Button.java:185)
    at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3758)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3486)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2495)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:350)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:275)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$350(GlassViewEventHandler.java:385)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$$Lambda$201/1104469783.get(Unknown Source)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:404)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:384)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:927)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$145(WinApplication.java:101)
    at com.sun.glass.ui.win.WinApplication$$Lambda$36/1963387170.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1765)
    ... 50 more
Caused by: java.lang.NullPointerException
    at FXMLDocumentController.AddClassButton(FXMLDocumentController.java:359)
    ... 60 more

这是我的FXML控制器文件:

import java.io.File;
import java.net.URL;
import java.time.DayOfWeek;
import java.util.ArrayList;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javafx.animation.TranslateTransition;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.AnchorPane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.util.Duration;

public class FXMLDocumentController implements Initializable {
    String AttachedFilePath;
    int CourseAddPaneStatus = 0;
    Member signedin = new Member();
    FileManager FM = new FileManager();
    ObservableList<String> genderList = FXCollections.observableArrayList("Gender","خانم","آقا");
    ObservableList<String> gradeList = FXCollections.observableArrayList("Grade","ابتدایی","راهنمایی","دبیرستان","کاردانی","کارشناسی","کارشناسی ارشد","دکتری","تخصص");

    // First Page
    @FXML
    AnchorPane firstPage;



    // SignIn Page
    @FXML
    AnchorPane signInPage;



    // SignUp Page
    @FXML
    AnchorPane signUpPage;
    @FXML
    TextField SignUpNameTextField;
    @FXML
    TextField SignUpPasswordTextField;
    @FXML
    TextField SignUpUserNameTextField;
    @FXML
    TextField SignUpEmailTextField;
    @FXML
    TextField SignUpCityTextField;
    @FXML
    TextField SignUpSchoolTextField;
    @FXML
    PasswordField SignUpPasswordField;
    @FXML
    ChoiceBox<String> SignUpGenderChoiceBox;
    @FXML
    ChoiceBox<String> SignUpGradeChoiceBox;
    @FXML
    Label SignUpInvalidEmailLabel;
    @FXML
    Label SignUpInvalidGenderLabel;
    @FXML
    Label SignUnInvalidUsernameLabel;
    @FXML
    Label SignUpInvalidGradeLabel;
    @FXML
    Label SignUpEmptyLabel;
    @FXML
    ToggleButton PasswordToggleButton;
    @FXML
    Label SignUpTakenEmailLabel;



    // Course List
    @FXML
    AnchorPane CourseListPage;
    @FXML
    AnchorPane ClassAddPane;
    @FXML
    Button ClassListAddButton;
    @FXML
    CheckBox CourseAddShanbeChoiceBox;
    @FXML
    CheckBox CourseAddYekShanbeChoiceBox;
    @FXML
    CheckBox CourseAddDoShanbeChoiceBox;
    @FXML
    CheckBox CourseAddSeShanbeChoiceBox;
    @FXML
    CheckBox CourseAddCharShanbeChoiceBox;
    @FXML
    CheckBox CourseAddPanjShanbeChoiceBox;
    @FXML
    TextField CourseAddNameTextField;
    @FXML
    TextField CourseAddStartHourTextField;
    @FXML
    TextField CourseAddStartMinuteTextField;
    @FXML
    TextField CourseAddFinishHourTextField;
    @FXML
    TextField CourseAddFinishMinuteTextField;
    @FXML
    Button ClassAddFileButton;
    @FXML
    Button ClassAddButton;
    @FXML
    Label AddClassFillTextFieldsErrorLabel;
    @FXML
    Label AddClassNoDaysErrorLabel;
    @FXML
    Label AddClassWrongClockErrorLabel;
    @FXML
    Label AddClassAttachedFilePath;

    @FXML
    private void PasswordToggleButton (ActionEvent event) {
        if(PasswordToggleButton.isSelected()) {
            SignUpPasswordTextField.setText(SignUpPasswordField.getText());
            SignUpPasswordField.setVisible(false);
            SignUpPasswordTextField.setVisible(true);
        } else {
            SignUpPasswordField.setText(SignUpPasswordTextField.getText());
            SignUpPasswordField.setVisible(true);
            SignUpPasswordTextField.setVisible(false);
        }
    }

    @FXML
    private void FPSignInButton (ActionEvent event) {
        firstPage.setVisible(false);
        signInPage.setVisible(true);
    }

    @FXML
    private void SignUpButton (ActionEvent event) {
        int status = 0; // 8 = Complete // 0-7 = Not Complete!

        if(SignUpNameTextField.getText().isEmpty() || SignUpUserNameTextField.getText().isEmpty() || SignUpEmailTextField.getText().isEmpty() || SignUpCityTextField.getText().isEmpty() || SignUpSchoolTextField.getText().isEmpty() || SignUpPasswordField.getText().isEmpty()) {
            SignUpEmptyLabel.setVisible(true);
            return;
        } else {
            SignUpEmptyLabel.setVisible(false);
        }
        Member newmember = new Member();

        // Name
        newmember.setName(SignUpNameTextField.getText());
        status++;

        // Username
        int usernamestatus = 0;
        for(Member m: FM.read()) {
            if((m.getUsername().compareTo(SignUpUserNameTextField.getText())) == 0) {
                usernamestatus++;
            }
        }
        if(usernamestatus == 0) {
            newmember.setUsername(SignUpUserNameTextField.getText());
            status++; 
            SignUnInvalidUsernameLabel.setVisible(false);
        } else {
            SignUnInvalidUsernameLabel.setVisible(true);
        }

        // Email
        String validEmail = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,8}$";
        Pattern pattern = Pattern.compile(validEmail, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(SignUpEmailTextField.getText());
        if(!matcher.matches()) {
            SignUpInvalidEmailLabel.setVisible(true);
        } else {
            int emailstatus = 0;
        for(Member m: FM.read()) {
            if((m.getEmail().compareTo(SignUpEmailTextField.getText())) == 0) {
                emailstatus++;
            }
        }
        if(emailstatus == 0) {
            newmember.setEmail(SignUpEmailTextField.getText());
            status++; 
            SignUpInvalidEmailLabel.setVisible(false);
            SignUpTakenEmailLabel.setVisible(false);
        } else {
            SignUpTakenEmailLabel.setVisible(true);
        }
        }

        // Grade
        if(SignUpGradeChoiceBox.getValue().equals("Grade")) {
            SignUpInvalidGradeLabel.setVisible(true);
        } else {
            newmember.setGrade(SignUpGradeChoiceBox.getValue());
            SignUpInvalidGradeLabel.setVisible(false);
            status++;
        }

        // Gender
        if(SignUpGenderChoiceBox.getValue().equals("Gender")) {
            SignUpInvalidGenderLabel.setVisible(true);
        } else {
            newmember.setGender(SignUpGenderChoiceBox.getValue());
            SignUpInvalidGenderLabel.setVisible(false);
            status++;
        }

        // City
        newmember.setCity(SignUpCityTextField.getText());
        status++;

        // School
        newmember.setSchool(SignUpSchoolTextField.getText());
        status++;

        // Password
        if(PasswordToggleButton.isSelected()) {
            newmember.setPassword(SignUpPasswordTextField.getText());
        } else {
            newmember.setPassword(SignUpPasswordField.getText());
        }
        status++;

        if(status==8) {
            ArrayList<Member> temp = new ArrayList<>();
            temp = FM.read();
            temp.add(newmember);
            FM.write(temp);
            signedin = newmember;
            signUpPage.setVisible(false);
            CourseListPage.setVisible(true);
        }


    }

    @FXML
    private void FPSignUpButton (ActionEvent event) {
        firstPage.setVisible(false);
        signUpPage.setVisible(true);
    }

    @FXML
    private void ReturnToFirstPageButton (ActionEvent event) {
        firstPage.setVisible(true);
        signUpPage.setVisible(false);
        signInPage.setVisible(false);
    }

    @FXML
    private void ClassAddPaneButton (ActionEvent event) throws InterruptedException {
        if(CourseAddPaneStatus == 0) {
            CourseAddPaneStatus = 1;
            ClassAddPane.setVisible(true);
            TranslateTransition cominginbutton = new TranslateTransition();
            cominginbutton.setDuration(Duration.millis(800));
            cominginbutton.setByX(-408);
            cominginbutton.setNode(ClassListAddButton);
            TranslateTransition cominginpane = new TranslateTransition();
            cominginpane.setDuration(Duration.millis(800));
            cominginpane.setByX(-408);
            cominginpane.setNode(ClassAddPane);
            cominginbutton.play();
            cominginpane.play();
        } else {
            CourseAddPaneStatus = 0;
            TranslateTransition cominginbutton = new TranslateTransition();
            cominginbutton.setDuration(Duration.millis(900));
            cominginbutton.setByX(408);
            cominginbutton.setNode(ClassListAddButton);
            TranslateTransition cominginpane = new TranslateTransition();
            cominginpane.setDuration(Duration.millis(900));
            cominginpane.setByX(408);
            cominginpane.setNode(ClassAddPane);
            cominginbutton.play();
            cominginpane.play();
        }
    }

    @FXML
    private void ExitButton (ActionEvent event) {
        System.exit(0);
    }

    @FXML
    private void AddClassButton (ActionEvent event) {
        int status = 0;
        if(CourseAddNameTextField.getText().isEmpty() 
                || CourseAddStartHourTextField.getText().isEmpty() 
                || CourseAddStartMinuteTextField.getText().isEmpty() 
                || CourseAddFinishHourTextField.getText().isEmpty() 
                || CourseAddFinishMinuteTextField.getText().isEmpty()) {
            AddClassFillTextFieldsErrorLabel.setVisible(true);
            status++;
        } else {
            AddClassFillTextFieldsErrorLabel.setVisible(false);
        }
        if(!CourseAddShanbeChoiceBox.isSelected() 
                && !CourseAddYekShanbeChoiceBox.isSelected() 
                && !CourseAddDoShanbeChoiceBox.isSelected() 
                && !CourseAddSeShanbeChoiceBox.isSelected() 
                && !CourseAddCharShanbeChoiceBox.isSelected() 
                && !CourseAddPanjShanbeChoiceBox.isSelected()) {
            AddClassNoDaysErrorLabel.setVisible(true);
            status++;
        } else {
            AddClassNoDaysErrorLabel.setVisible(false);            
        }
        if(!isNumber(CourseAddStartHourTextField.getText()) 
                || !isNumber(CourseAddStartMinuteTextField.getText()) 
                || !isNumber(CourseAddFinishHourTextField.getText()) 
                || !isNumber(CourseAddFinishMinuteTextField.getText())) {
            AddClassWrongClockErrorLabel.setVisible(true);
            status++;
        } else {
            if(Integer.parseInt(CourseAddStartHourTextField.getText())<0 
                    || Integer.parseInt(CourseAddStartHourTextField.getText())>23
                    || Integer.parseInt(CourseAddFinishHourTextField.getText())<0
                    || Integer.parseInt(CourseAddFinishHourTextField.getText())>23
                    || Integer.parseInt(CourseAddStartMinuteTextField.getText())<0
                    || Integer.parseInt(CourseAddStartMinuteTextField.getText())>59
                    || Integer.parseInt(CourseAddFinishMinuteTextField.getText())<0
                    || Integer.parseInt(CourseAddFinishMinuteTextField.getText())>59) {
            AddClassWrongClockErrorLabel.setVisible(true);
            status++;
            } else {
            AddClassWrongClockErrorLabel.setVisible(false);

            }
        }
        if(status!=0) {
            return;
        }
        Class newclass = new Class();
        ArrayList<DayOfWeek> classdays = new ArrayList();
        newclass.setSubject(CourseAddNameTextField.getText());
        if(CourseAddShanbeChoiceBox.isSelected()) classdays.add(DayOfWeek.SATURDAY);
        if(CourseAddYekShanbeChoiceBox.isSelected()) classdays.add(DayOfWeek.SUNDAY);
        if(CourseAddDoShanbeChoiceBox.isSelected()) classdays.add(DayOfWeek.MONDAY);
        if(CourseAddSeShanbeChoiceBox.isSelected()) classdays.add(DayOfWeek.TUESDAY);
        if(CourseAddCharShanbeChoiceBox.isSelected()) classdays.add(DayOfWeek.WEDNESDAY);
        if(CourseAddPanjShanbeChoiceBox.isSelected()) classdays.add(DayOfWeek.THURSDAY);
        newclass.setDayofweek(classdays);
        newclass.setStarttimehour(Integer.parseInt(CourseAddStartHourTextField.getText()));
        newclass.setStarttimeminute(Integer.parseInt(CourseAddStartMinuteTextField.getText()));
        newclass.setStarttimehour(Integer.parseInt(CourseAddStartHourTextField.getText()));
        newclass.setStarttimeminute(Integer.parseInt(CourseAddStartMinuteTextField.getText()));
        newclass.setAttachedfile(AttachedFilePath);
        ArrayList<Class> ar = signedin.getClasses();
        ar.add(newclass);
        signedin.setClasses(ar);
        for(Member m: FM.read()) {
            if((m.getUsername().compareTo(signedin.getUsername())) == 0) {
                int c = FM.read().indexOf(m);
                ArrayList<Member> updatedarray = new ArrayList();
                updatedarray.set(c, signedin);
                FM.write(updatedarray);
            }
        }
    }

    @FXML
    private void ChooseFileButton (ActionEvent event) {
        FileChooser chooser = new FileChooser();
        chooser.setTitle("Open File");
        File file = chooser.showOpenDialog(new Stage());
        AttachedFilePath = file.getPath();
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        SignUpGenderChoiceBox.setValue("Gender");
        SignUpGradeChoiceBox.setValue("Grade");
        SignUpGenderChoiceBox.setItems(genderList);
        SignUpGradeChoiceBox.setItems(gradeList);


    }

    private boolean isNumber(String s) {
        try {
            Integer.parseInt(s);
            return true;
        } catch (NumberFormatException e){
            return false;
        }
    }

}

在为按钮添加“ AddClassButton”处理程序之前未发生错误,该按钮应该获取有关类的信息并将其保存在成员的信息中

这些是您可能需要了解的可能的类:

会员:

import java.io.Serializable;
import java.util.ArrayList;



public class Member implements Serializable {

    private final String RED = "\u001B[31m";
    private final String RESET = "\u001B[0m";
    private static final long serialVersionUID = 6529685098267757690L;


    private String name;
    private String username;
    private String password;
    private String gender;
    private String grade;
    private String city;
    private String School;
    private String email;
    private ArrayList<Class> classes;

    // Methods

    public void addNewClass(Class a) {
        this.classes.add(a);
    }

    // Getters 

    public ArrayList<Class> getClasses() {
        return classes;
    }

    public String getName() {
        return name;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public String getGrade() {
        return grade;
    }

    public String getCity() {
        return city;
    }

    public String getSchool() {
        return School;
    }

    public String getGender() {
        return gender;
    }

    public String getEmail() {
        return email;
    }

    // Setters

    public void setName(String name) {
        this.name = name;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public void setSchool(String School) {
        this.School = School;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public void setClasses(ArrayList<Class> classes) {
        this.classes = classes;
    }

}

班级:

import java.time.DayOfWeek;
import java.util.ArrayList;

public class Class {
    private String subject;
    private ArrayList<DayOfWeek> dayofweek;
    private int starttimehour;
    private int starttimeminute;
    private int finishtimehour;
    private int finishtimeminute;
    private String note;
    private String attachedfilepath;

    // Getters
    public int getStarttimehour() {
        return starttimehour;
    }

    public int getStarttimeminute() {
        return starttimeminute;
    }

    public int getFinishtimehour() {
        return finishtimehour;
    }

    public int getFinishtimeminute() {    
        return finishtimeminute;
    }

    public String getSubject() {
        return subject;
    }

    public ArrayList<DayOfWeek> getDuedate() {
        return dayofweek;
    }

    public String getNote() {
        return note;
    }

    public String getAttachedfile() {
        return attachedfilepath;
    }

    // Setters

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public void setDayofweek(ArrayList<DayOfWeek> dayofweek) {
        this.dayofweek = dayofweek;
    }

    public void setStarttimehour(int starttimehour) {
        this.starttimehour = starttimehour;
    }

    public void setStarttimeminute(int starttimeminute) {
        this.starttimeminute = starttimeminute;
    }

    public void setFinishtimehour(int finishtimehour) {
        this.finishtimehour = finishtimehour;
    }

    public void setFinishtimeminute(int finishtimeminute) {
        this.finishtimeminute = finishtimeminute;
    }

    public void setNote(String note) {
        this.note = note;
    }

    public void setAttachedfile(String attachedfile) {
        this.attachedfilepath = attachedfile;
    }
}

最后是FileManager:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class FileManager {

    private File file = new File("datastg.data3");

    public FileManager() {
        try {
            if(!file.exists()) {
                file.createNewFile();
                ArrayList<Member> Base = new ArrayList();
                Member j = new Member();
                j.setCity("0");
                j.setEmail("0");
                j.setGender("0");
                j.setName("0");
                j.setPassword("0");
                j.setSchool("0");
                j.setUsername("0");
                j.setGrade("0");
                Base.add(j);
                this.write(Base);
            }
        } catch(Exception e) {
            e.printStackTrace();
        }

    }




    public void write(ArrayList<Member> list) {
        try {
            FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(list);
            oos.flush();
            oos.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public ArrayList<Member> read(){
        try {
            FileInputStream fis = new FileInputStream(file);
            ObjectInputStream ois = new ObjectInputStream(fis);
            ArrayList<Member> list = (ArrayList<Member>) ois.readObject();
            ois.close();
            return list;
        } catch(IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}

0 个答案:

没有答案