为什么在jdk的帮助文档里不推荐使用save方法而应使用store方法,原因是This method does not throw an IOException if an I/O error occurs while saving the property list.
但properties的src中的两个方法:
public synchronized void save(OutputStream outputstream, String s)
    {
        try
        {
           //.......................
        }
        catch(IOException ioexception) { }
    }public synchronized void store(OutputStream outputstream, String s)
        throws IOException
    {
          //........................
    }
一个在里面捕捉,一个在外面抛出,有什么不同呢,为什么后者才是安全的呢!

解决方案 »

  1.   

    因为如果你调用save方法,外面的程序根本不知道保存成功还是失败了
    但是使用store方法的时候,外面的程序可以根据有没有异常来判断保存是不是成功了外面程序很可能需要判断这个成功标记的这个就是两个方法的区别
      

  2.   

    如果我的调用程序中用
    try {p.store(new FileOutputStream("messages.properties"),"messages");}
    catch (FileNotFoundException e) {}
    catch(IOException e) {}    //#1try {p.save(new FileOutputStream("messages.properties"),"messages");}
    catch (FileNotFoundException e) {}
    catch(IOException e) {}    //#2
    那么就是说这时如果只发生了IO异常的话,#2的还是会正常运行喽,还有怎样才能让它发生IO异常,我想debug看到效果
      

  3.   

    楼上说的有错误:
    #2也会报异常的。
    因为java的异常机制是逐层上报,也就是说,只要是下面有异常,上面肯定会捕捉到的。
      

  4.   

    如果也报异常的话,那么用save是不是也无碍?
      

  5.   

    不是这个意思
    改一下代码
    FileOutputStream fos = new FileOutputStream("messages.properties");
    try {p.store(fos, "messages");}
    catch (FileNotFoundException e) {}
    catch(IOException e) {}    //#1try {p.save(fos, "messages");}
    catch (FileNotFoundException e) {}
    catch(IOException e) {}    //#2这样就造成了#2编译不过。
    你上面的那种写法,IOException是在new FileOutputStream的时候产生的,而不是save中
    所以你是无法判断到底是不是真的保存成功了,即使没有产生异常
      

  6.   

    to ChDw(米):
    是不是可以这样理解,我用save方法,只能捕捉到FileNotFoundException ,而不能捕捉到IOException,即使在p.save()方法中出现了并在其中catch了,对于外部来说是不可视的,而不能确定save是否成功
            Properties p = new Properties();
            try {
                FileOutputStream fos = new FileOutputStream("messages.properties");
                p.save(fos, "messages");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
    而用store方法,在外部可以通过是否会发生IOException来判断当前的store操作是否成功
            Properties p = new Properties();
            try {
                FileOutputStream fos = new FileOutputStream("messages.properties");
                p.store(fos, "messages");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
      

  7.   

    对,应该这个意思,所以JDK后来的版本才把save方法变成过时的