如何在属性文件中搜索元素?

时间:2015-05-28 11:00:22

标签: java file search

要求是:
发票编号将从XSLT传递,根据发票编号,我必须增加与该发票编号对应的计数器。

示例:invoice=1020从XSLT传递,我必须阅读该发票并在文件中搜索它是否存在。如果是,则递增计数器(count=prev_count+1)。 如果没有,请在文件中写入发票号并将其初始化为1.

如何实现这一要求?

提前致谢。

public static void LookupInsert( int invoiceNumber)
    {
        Properties properties = new Properties();
        File propertiesfile = new File("Sequence.properties");
        if(propertiesfile.length()==0)
        {
            try{
                propertiesfile.createNewFile();
                properties.load(new FileInputStream(propertiesfile));
            } catch (IOException e) {
                e.printStackTrace();
            }
            int value=1;
            properties.setProperty(new Integer(invoiceNumber).toString(), new Integer(value).toString());
        }

        try {
            propertiesfile.createNewFile();
            properties.load(new FileInputStream(propertiesfile));
        } catch (IOException e) {
            e.printStackTrace();
        }
        Properties props = System.getProperties();
        if(props.get(invoiceNumber)== null)
        {
            int value=1;
            props.setProperty(new Integer(invoiceNumber).toString(), new Integer(value).toString());
            try {
                properties.store(new FileOutputStream(propertiesfile), null);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else
        {
            int value = Integer.parseInt(props.get(invoiceNumber).toString());
            value++;
            props.setProperty(new Integer(invoiceNumber).toString(), new Integer(value).toString());
            try {
                properties.store(new FileOutputStream(propertiesfile), null);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    // main() is used for testing
    public static void main(String[] a) {
        LookupInsert(101);
        LookupInsert(101);
        LookupInsert(101);
    }
}

但是上面的代码是创建文件,但它没有在文件中更新值..

1 个答案:

答案 0 :(得分:0)

希望下面是您正在寻找的代码..

public void LookupInsert(int invoiceNumber)
{
    Properties props = System.getProperties();
    //if there is no invoice number in properties file then get(invoiceNumber) will be null
    if(props.get(invoiceNumber)== null)
        props.setProperty(new Integer(invoiceNumber).toString(), new Integer(1).toString());
    else
    {
        int value = Integer.parseInt(props.get(invoiceNumber).toString());
        value++;
        props.setProperty(new Integer(invoiceNumber).toString(), new Integer(value).toString());
    }
File file =new File("test.properties");
FileWriter fw = new FileWriter(file);
props.store(fw,"");
fw.close();
}