繁体   English   中英

用Java将队列写入属性文件

[英]Writing a queue to a properties file in Java

有没有一种简单的方法可以将队列写到Java文件中以便可以回读?

我的程序当前以逗号分隔格式将数组保存到属性文件中。 这很容易,因为可以迭代数组。

我的程序还具有队列功能。 我唯一的选择是使用队列,以便在我想将队列的所有元素写入文件时从队列中删除所有项目并重新添加它们吗?

实现此目的最简单的方法是什么?

理想情况下,我希望将信息保存在其他阵列写入的相同属性文件中。

您可以尝试这样的事情:

FileOutputStream fos = null;
ObjectOutputStream os = null;

try {
    fos = new FileOutputStream(YOUR_FILE_NAME);
    os = new ObjectOutputStream(fos);

    for(YourObjectType current : YourQueue){
        os.writeXXX(current);  //Where XXX is the appropriate write method depending on your data type
        os.writeChars(",");  //Since you mentioned wanting a comma delimiter..
    }
} catch(IOException e){
   e.printStackTrace(); 
} finally {
    if(fos != null) fos.close();
    if(os != null) os.close();
}

最简单的解决方案是将队列写为单个集合。

public static void write(String filename, Collection queue) throws IOException {
    try(ObjectOutputStream oos = new ObjectObjectStream(new FileOutputStream(filename))) {
        oos.writeObject(queue);
    }
}

读这个

public static void read(String filename, Collection toAddTo) throws IOException, ClassNotFoundException {
    try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) {
        toAddTo.addAll((Collection) ois.readObject());
    }
}

暂无
暂无

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

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