将数组的对象存储到CSV文件中,并使用GUI的特定参数读取它们

时间:2016-12-03 16:23:04

标签: java arrays swing csv arraylist

作为我的任务的一部分,我必须将数组的对象存储在平面文件中,并在满足某些条件时检索它们。我可以保存对象很好但是在检索它们时我遇到了一个问题,我得到了多个值,我明白出了什么问题,但我很难找到解决方案。这是最新发生的概念。

按钮号10,A(代码中的R1S10)是我的测试按钮,当我点击它时会创建一个我将在下面显示的事件。

This is my system, its a ticket booking system 单击事件按钮10A -

private void R1S10ActionPerformed(java.awt.event.ActionEvent evt) {                                      

    seats.add(seat1);


    if (R1S10.getBackground().equals(Color.red) &&(IsSeatBooked().equals("true"))){
        Component frame = null;
        JOptionPane.showMessageDialog(frame, "Seat UnBooked");
        seat1.setBooked("false");
        seat1.setName("");
        R1S10.setBackground(Color.yellow);
        try {
               reader();
            writer();

            //String booked = "true";
            //Pass String booked into csv file
        } catch (IOException ex) {
            Logger.getLogger(SeatingPlan.class.getName()).log(Level.SEVERE, null, ex);
        }

    } 
    else{
        Component frame = null;
        String name = JOptionPane.showInputDialog(frame, "Please enter name of Customer booking");
        if (name.isEmpty()) {
            JOptionPane.showMessageDialog(frame, "No value entered");

        } else if (name != null) {
            seat1.setName(name);
            seat1.setBooked("true");
            R1S10.setBackground(Color.red);
            JOptionPane.showMessageDialog(frame, "Your Booking has been placed");
            try {
                writer();
                reader();
                //String booked = "true";
                //Pass String booked into csv file
            } catch (IOException ex) {
                Logger.getLogger(SeatingPlan.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

}    

按照下面的屏幕 - When 10A is first pressed
结果 -

When booking is complete

再次按下该按钮时 -

UnBooked

我在这个SeatingPlan.java中使用了三个方法 - writer(),reader()和IsSeatBooked()。

SeatingPlan -

public class SeatingPlan extends javax.swing.JFrame {

/**
 * Creates new form SeatingPlan
 */
String seatNo, name, bookedSeat;
FileWriter fileWriter = null;
List<Seat> seats = new ArrayList<Seat>();


//Seat Object Declaration

Seat seat1 = new Seat("R1S10","","false");
Seat seat2 = new Seat("R1S9", "", "false");
String fileName = "seat.csv";

作家 -

 public void writer() throws IOException {
    //Delimiter used in CSV file
    final String NEW_LINE_SEPARATOR = "\n", COMMA_DELIMITER = ",";

    //CSV file header
    final String FILE_HEADER = "seatID,name,booked";

    //fileName = System.getProperty("user.home") + "/seat.csv";
    try {
        fileWriter = new FileWriter(fileName);

        //Write the CSV file header
        fileWriter.append(FILE_HEADER.toString());

        //Add a new line separator after the header
        fileWriter.append(NEW_LINE_SEPARATOR);

        //Write a new student object list to the CSV file
        for (Seat seat : seats) {
            fileWriter.append(String.valueOf(seat.getSeatID()));
            fileWriter.append(COMMA_DELIMITER);
            fileWriter.append(seat.getName());
            fileWriter.append(COMMA_DELIMITER);
            fileWriter.append(seat.isBooked());
            fileWriter.append(NEW_LINE_SEPARATOR);
        }

        System.out.println("CSV file was created successfully !!!");

    } catch (Exception e) {
        System.out.println("Error in CsvFileWriter !!!");
        e.printStackTrace();
    } finally {

        fileWriter.flush();
        fileWriter.close();

    }
}

读者 -

public void reader() {
    //Delimiter used in CSV file
    final String COMMA_DELIMITER = ",";
    //Student attributes index
    final int SEAT_ID_IDX = 0;
    final int SEAT_NAME_IDX = 1;
    final int SEAT_BOOKED = 2;
    //private static final int STUDENT_LNAME_IDX = 2;
    BufferedReader fileReader = null;

    try {

        //Create a new list of student to be filled by CSV file data 
        List<Seat> seats = new ArrayList<>();

        String line = "";

        //Create the file reader
        fileReader = new BufferedReader(new FileReader(fileName));

        //Read the CSV file header to skip it
        fileReader.readLine();

        //Read the file line by line starting from the second line
        while ((line = fileReader.readLine()) != null) {
            //Get all tokens available in line
            String[] tokens = line.split(COMMA_DELIMITER);
            if (tokens.length > 0) {
                //Create a new seat object and fill his  data
                Seat seat = new Seat(tokens[SEAT_ID_IDX],           
                tokens[SEAT_NAME_IDX], tokens[SEAT_BOOKED]);
                seats.add(seat);
                seatNo = tokens[SEAT_ID_IDX];
               //System.out.println("Seat Number: " + seatNo);
                bookedSeat = tokens[SEAT_BOOKED];
              }
        }

        //Print the new student list
        for (Seat seat : seats) {
            System.out.println(seat.toString());
        }
    } catch (Exception e) {
        System.out.println("Error in CsvFileReader !!!");
        e.printStackTrace();
    } finally {
        try {
            fileReader.close();
        } catch (IOException e) {
            System.out.println("Error while closing fileReader !!!");
            e.printStackTrace();
        }
    }

}//end reader

SeatingPlan - 如果我试图控制结果的参数,但是当选择多个席位时IsBooked发生碰撞。

 public SeatingPlan() throws IOException {
    setVisible(true);
    initComponents();
    //reader();
    ColourSectionGold();
    ColourSectionBronze();
    reader();

    if(R1S10.getBackground().equals(Color.yellow) && (IsSeatBooked().equals("true"))){ R1S10.setBackground(Color.red);}
    //if(R1S9.getBackground().equals(Color.yellow) && (IsSeatBooked().equals("true2"))){ R1S9.setBackground(Color.red);}
   }

IsSeatBooked -

 public String IsSeatBooked(){
 return bookedSeat;   
}//end IsSeatBooked 

我使用上面的方法作为我的参数来查看座位是否被预订,但是当新座位被点击时,它设置了'registeredSeat'的整个值 - 这使得系统无法正常工作。我理解代码不是很有效但是如果我已经正确解释了这个问题是否有任何临时修复。

此外,我将把我的课程包括在座位 -

public class Seat {
private String seatID;
private String booked;
private String name;
private int price;

public Seat(String seatID,String name,String booked){
    this.seatID = seatID;
    this.booked = "";
    this.name = name;
    this.price = price;
}

public String getSeatID() {
    return seatID;
}

public void setSeatID(String seatID) {
    this.seatID = seatID;
}

public String isBooked() {
    return booked;
}

public void setBooked(String booked) {
   this.booked = booked;
}

public String getStatus(){
    return booked;
}

public String getName() {
    return name;
}

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

public void setPrice() {
   this.price = price;
}}//end class Seat 

查看创建的CSV文件 -

CSV Outcome

我希望能够单击多个按钮并保存其状态,此时Button 10正常工作,但因为IsBooked一次只有一个值,所以它会发生冲突。

如果你花时间检查一下,我很感激。任何建设性的批评都是有帮助的,任何想法都会很棒!

谢谢, 稻田。

1 个答案:

答案 0 :(得分:1)

要查看的代码太多,无法确切了解自己在做什么。

您可以创建Properties文件,而不是使用csv文件。 Properties文件将以以下形式存储数据:

key:data

因此,在您的情况下,密钥将是id:A1,A2 ......并且数据将是预订座位的人的姓名。

因此该文件将以空白开头。创建GUI时,您将创建一个循环,检查每个id以查看是否在“属性”字段中找到了条目。如果找到,则显示座位为已拍摄,否则为空。

然后,只要您想预订座位,就可以使用setProperty(...)方法。

Properties班级有load(...)store(...)个方法。

因此Properties类允许您轻松管理平面文件数据库。

注意,你永远不会有像R1S10这样的变量名。这将要求使用if / else语句的100个不同变量。相反,你会扩展JButton并传入行和座位作为参数按钮。然后在该按钮的ActionListener中,您可以访问行/席位信息以构建用作属性文件的键的ID。

编辑:

  

无法完成检查ID是否在属性文件中的循环。

如果属性为null,则seath为空。

import java.util.*;

public class Main
{
    public static void main(String[] args)
    {
        Properties properties = new Properties();
        properties.setProperty("A2", "Smith");
        properties.setProperty("C3", "Jones");

        String[] rows = { "A", "B", "C", "D" };
        int seats = 4;

        for (int row = 0; row < rows.length; row++)
        {
            for (int seat = 1; seat <= seats; seat++)
            {
                String key = rows[row] + seat;
                String property = properties.getProperty( key );

                System.out.println(key + " : " + property);
            }
        }


    }
}