简体   繁体   English

文件写入和读取不工作 Java

[英]File Writing and Reading not working Java

I am trying to make a simple GUI app that takes strings and a button and saves it to a file.我正在尝试制作一个简单的 GUI 应用程序,它接受字符串和按钮并将其保存到文件中。 When the app loads, the fields are populated with the values in the text file, which will look like this:当应用程序加载时,这些字段将填充文本文件中的值,如下所示:

School Name学校名称
Selected Radio Button选定的单选按钮
Date日期

When I change the values in the GUI it will overwrite the above values in the text file.当我更改 GUI 中的值时,它将覆盖文本文件中的上述值。 The program populates the gui fields by reading line by line.该程序通过逐行读取来填充 gui 字段。

As I have my program now it gets an array Index out of bounds exception and it does not save anything to the file.由于我现在有我的程序,它得到了一个数组索引越界异常,并且它不会将任何内容保存到文件中。

here is the stacktrace:这是堆栈跟踪:

  Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at prog24178.TestingFiles.<init>(TestingFiles.java:66)
    at prog24178.TestingFiles.main(TestingFiles.java:88)

here is the code:这是代码:

public class TestingFiles extends JFrame {
    private JTextField txtCollege;
    private JTextField txtDate;
    public ArrayList <School> schools;
    String file = "c:\\Temp\\schools.txt";


    public TestingFiles(){
        super("Testing Files");
        getContentPane().setLayout(null);

        txtCollege = new JTextField();
        txtCollege.setBounds(0, 0, 359, 20);
        getContentPane().add(txtCollege);
        txtCollege.setColumns(10);

        JRadioButton selComp = new JRadioButton("Computers");
        selComp.setBounds(10, 27, 109, 23);
        getContentPane().add(selComp);

        JRadioButton selEng = new JRadioButton("Engineering");
        selEng.setBounds(139, 27, 109, 23);
        getContentPane().add(selEng);

        JRadioButton selArt = new JRadioButton("Arts");
        selArt.setBounds(281, 27, 78, 23);
        getContentPane().add(selArt);

        ButtonGroup bg = new ButtonGroup();
        bg.add(selArt);bg.add(selEng);bg.add(selComp);

        txtDate = new JTextField();
        txtDate.setBounds(0, 57, 359, 20);
        getContentPane().add(txtDate);
        txtDate.setColumns(10);

        JButton btnSave = new JButton("Save");
        btnSave.setBounds(0, 77, 183, 34);
        getContentPane().add(btnSave);
        btnSave.addActionListener(new SaveActionHandler());

        JButton btnExit = new JButton("Exit");
        btnExit.setBounds(183, 77, 176, 34);
        getContentPane().add(btnExit);
        btnExit.addActionListener(new ExitHandler());


        schools = new ArrayList <School>();
        try{
            File f = new File(file);
            Scanner s = new Scanner (f);
            while (s.hasNextLine()){
                String line  = s.nextLine();
                String [] fields = line.split("/n");
                //schools.add(new School(fields[0], fields[1], fields[2])); ***Array Index out of bounds
            }
            s.close();
        }
        catch (IOException ioe){}
    }


    class SaveActionHandler implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            schools.add(new School(txtCollege.getText(),txtDate.getText() ));
        }       
    }
    class ExitHandler implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            System.exit(0);     
        }       
    }


    public static void main(String[] args) {
        TestingFiles app = new TestingFiles();
        app.setSize(375,150);
        app.setVisible(true);
        app.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    }
}
class School  {
    private String college;
    private String field;
    private String date;
    public School() {};
    public School(String college, String field,  String date){
        this.college = college;
        this.field = field;
        this.date = date;
    }
    public String getCollege() {
        return college;
    }
    public String getField() {
        return field;
    }
    public String getDate() {
        return date;
    }
    public void setCollege(String college) {
        this.college = college;
    }
    public void setField(String field) {
        this.field = field;
    }
    public void setDate(String date){
        this.date = date;
    }
}

Look at this code:看看这段代码:

File f = new File(file);
Scanner s = new Scanner (f);
while (s.hasNextLine()){
    String line  = s.nextLine();
    String [] fields = line.split("/n");
...

You're getting a line from the file and then trying to split it on the newline character.您从文件中获取一行,然后尝试将其拆分为换行符。 Scanner#nextLine() by default gives you everything from its current position up to the next newline. Scanner#nextLine()默认为您提供从当前位置到下一个换行符的所有内容。 In that case, a String returned by Scanner#nextLine() will never contain a newline, so your fields array will only ever contain one item, the entire line .在这种情况下, Scanner#nextLine()返回的String永远不会包含换行符,因此您的fields数组将只包含一项,即整line So when you try to access fields[1] you get the exception.因此,当您尝试访问fields[1]您会遇到异常。

An easy way you could have figured this out yourself, since you know the line that has the problem start there and work backwards to verify your assumptions.一种简单的方法,您可以自己解决这个问题,因为您知道有问题的生产线从那里开始并反向工作以验证您的假设。 The first assumption you should verify is that fields contains the number of fields you expect.您应该验证的第一个假设是fields包含您期望的字段数。

String [] fields = line.split("/n");
System.out.println("fields contains " + fields.length + " items");

That would have told you that fields only contains one item.那会告诉您fields仅包含一项。

The next assumption to verify would be that line actually contains newlines.下一个要验证的假设是该line实际上包含换行符。

String line  = s.nextLine();
System.out.println("Line is " + line);

Ahh, there's the problem!啊,问题来了! line doesn't contain any newlines and you're trying to split on newlines. line 不包含任何换行符,并且您试图在换行符上拆分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM