如何使用Java中的BufferWriter保存到文件

时间:2015-11-19 16:34:06

标签: java file save load

我目前正在创建一个保存/加载字符串的文件。我目前在下面有这个代码,但它目前无法正常工作。该文件将如下所示

E.G。

1,Joey,Duncan,98 Fallout Lane,FL78 5FY,true

2,Iain,Watt,1 Golf Lane,GL01 6KW,0.463,false

public void loadData(File f){
        String file ="items.txt";  
        try {
            try (Scanner scnr = new Scanner((f))) {
                scnr.useDelimiter(",|\n");
                while(scnr.hasNext()){
                    int type             = scnr.nextInt();
                    String firstName     = scnr.next();
                    String secondName    = scnr.next();
                    String address       = scnr.next();
                    String postcode      = scnr.next();
                    boolean isFirstClass = scnr.nextBoolean();

                    Person person        = new Person(firstName, secondName);
                    Addressee addressee  = new Addressee(person, address, postcode);

                    if (type == 1){
                        Letter l = new Letter(addressee, isFirstClass);
                        this.items.add(l);
                    } else if (type == 2){
                        double weight = scnr.nextDouble();
                        Parcel p = new Parcel(addressee, weight, isFirstClass) {};
                    } else{

                    }
                }
            }
        } catch (Exception ex) {
            System.out.println(ex);
            System.exit(1);
        }
    }

    public void saveData(File f){
        String file ="items.txt"; 
        try {
            try (BufferedWriter bw = new BufferedWriter(new FileWriter(f))) {
                for (MailItem m: items){
                    if (m instanceof Letter){
                        bw.write("1," + m.getAddressee() + m.isFirstClass());
                        bw.write("\n");
                    } else if (m instanceof Parcel){
                        bw.write("2," + m.getAddressee() + "," + ((Parcel)m).getWeight());
                        bw.write("," + m.isFirstClass() + "\n");
                    }
                }
                bw.flush();
                System.out.println(f);
            }
        } catch (Exception ex) {
            System.out.println(ex);
            System.exit(1);
        }
    }

0 个答案:

没有答案