将对象的ArrayList写入文件

时间:2014-12-24 03:44:10

标签: java serialization arraylist

public class Inventory implements Serializable {
    ArrayList<Product> productlist;
    File file;

    public Inventory(){
        productlist = new ArrayList<Product>();
        file = new File("build/classes/inventory/inv.ser");

        if(!file.exists()){
            try {
                file.getParentFile().mkdirs();
                file.createNewFile();

            } catch (IOException ex) {
                Logger.getLogger(Inventory.class.getName()).log(Level.SEVERE, null, ex);
            }        
        }

        if(file.length() !=0){
            loadFile(file);
        }
    }

    public void addProduct(Product product){
        productlist.add(product);
        saveFile(this.file);
    }

    public void saveFile(File file){                
        try{    
        FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream out = new ObjectOutputStream(fos);
            out.writeObject(productlist);
            out.close();
            fos.close();
        } catch(FileNotFoundException ex){System.out.println("FileNotFoundException");}
           catch(IOException ex){System.out.println("InputException");}                   
    }

    public void loadFile(File file){
            try{

            FileInputStream fis = new FileInputStream(file);
                ObjectInputStream in = new ObjectInputStream(fis);
                productlist=(ArrayList<Product>)in.readObject();
                in.close();
                fis.close();
            } catch(FileNotFoundException ex){ System.out.println("FileNotFoundException"); }
               catch(IOException ex){System.out.println("OutputException");} 
                catch(ClassNotFoundException ex){System.out.println("ClassNotFoundException");}

    }
}

writeObject()是否会覆盖现有文件的内容或将对象附加到现有文件中?

像我在saveFile方法中所做的那样序列化对象的ArrayList是个好主意吗?

2 个答案:

答案 0 :(得分:3)

  

writeObject()是否会覆盖现有文件的内容或将对象附加到现有文件中?

都不是。它将对象写入底层流。底层流是一个只能附加到的串行字节流。在这种情况下,底层流由底层文件支持,该文件已经已经已经被覆盖,具体取决于您构建FileOutputStream.的方式它没有任何内容与writeObject()有关。在任何情况下,如果不采取特殊措施,都无法成功附加到序列化对象的文件。

  

像在saveFile方法中所做的那样序列化对象的ArrayList是个好主意吗?

与什么相比?

N.B。

  1. 当您收到异常时,请将其打印出来。不只是你自己设计的一些信息。

  2. 创建一个文件只是为了让你可以测试零长度是没有意义的。

  3. 一旦停止使用IDE,目录build/classes/inventory将不会在运行时出现。这不是放置文件的地方。

答案 1 :(得分:0)

您可以尝试使用 FileUtils 函数将对象列表写入平面文本文件。 请在下面找到URL供参考-

http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#writeLines-java.io.File-java.util.Collection-java.lang.String-boolean-

例如 FileUtils.writeLines(新文件(fileToAttach),列表);