代码只将一行文本文件保存到数组中

时间:2012-12-05 13:07:34

标签: java arraylist save

我生成的代码旨在提供逐行读取文本文件的功能,将每行保存到数组中。它似乎正确地读取每一行,但是当我使用printProps()方法时,它只显示一个...

代码只将一行文本文件保存到数组中,我的代码出了什么问题?

/*reading in each line of text from text file and passing it to the processProperty() method.*/
Public void readProperties(String filename) {
    try {
        BufferedReader reader = new BufferedReader(new FileReader(filename));
        int i = 0;
        String line;
        line = reader.readLine();
        while (line != null && !line.equals("")) {
            i++;
            processProperty(line);
            line = reader.readLine();
        }
        System.out.println("" + i + " properties read");
    } catch (Exception e) {
        System.err.println(e.getMessage());
        e.printStackTrace();

    }
}

/*Breaks up the line of text in order to save the value to an array (at this point it only saves one line to the array). org.newProp(newProp) passes the new property to the Organize class where it saves it to an array.

public void processProperty(String line) {
         org = new Organize();
        int id = nextPropertyID;
        nextPropertyID++;

        String[] parts = line.split(":");
        int propNo = Integer.parseInt(parts[0]);            
        String postcode = parts[1];
        String type = parts[2];
        int bedrooms = Integer.parseInt(parts[3]);
        int year = Integer.parseInt(parts[4]);
        int rental = Integer.parseInt(parts[5]);
        Landlord landlord = theLandlord;
        Tenant tenant = null;
        org.propUniqueCheck(id);
        propNoCheck(propNo, postcode);
        postcodeCheck(postcode,propNo);
        typeCheck(postcode, propNo, type);
        bedroomsCheck(bedrooms, postcode, propNo);
        yearCheck(propNo, postcode, year);
        System.out.println("Creating property " + id);

        Property newProp = new Property(id, propNo, postcode, type, bedrooms, year,
                rental, landlord, tenant);
        org.newProp(newProp);
        org.printProps();
    }

/*From here down it is the code to save the value to the array*/

public Organize() {
        props = new ArrayList<Property>();
        PTs = new ArrayList<PotentialTenant>(); 
        waitingList = new LinkedList<String>();
        //myList.add(new prop(Property.toString()));

    }
    public void newProp(Property p)
    {
        props.add(p);
    }

我在研讨会上一直积极寻求这个问题的帮助,我似乎无法找到解决方案,非常感谢任何建议!

2 个答案:

答案 0 :(得分:1)

在processProperty中,您将实例化一个新的Organize对象。因此,每个属性(您为每一行创建的)都以不同的ArrayList(作为第一个元素)结束。

一种解决方案是在开始循环之前实例化一个Organize对象,然后将其作为参数传递给processProperty方法。

答案 1 :(得分:0)

当文本文件中的一行是空字符串时,你的while循环将会中断。

这是实现循环的正确方法:

String line = "";
while ((line = reader.readLine()) != null) {
    // your code here
}