【问题标题】:Writing a queue to a properties file in Java在 Java 中将队列写入属性文件
【发布时间】:2014-04-22 14:43:27
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 如果您使用的是Queue,您可以使用增强的for 循环遍历它,无需从中删除任何项目。

标签: java arrays properties stack queue


【解决方案1】:

你可以试试这样的:

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();
}

【讨论】:

  • 将字符写入 ObjectOutputStream 会使其非常难以阅读。您的意思是 writeObject() 而不是 write() 吗?你不能定义fosos两次。
  • 注意在cmets //根据你的对象类型选择合适的写方法。队列的底层数据类型从未在原始问题中提及,因此这篇文章更多是为了阐明 ObjectOutputStream API 的可用性并让 OP 从那里开始。感谢您指出双重声明,当我将其拉出到 finally 块时,我忘了删除它。
  • write() 仅在 YourObjectTypeBytebyte[] 时有效,任何其他类型都需要 writeObject()。
【解决方案2】:

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

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());
    }
}

【讨论】:

    猜你喜欢
    • 2017-12-19
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多