ITeye博客

为什么我上传后的文件无法从服务器删除?

yourgame · 2009-02-08 23:20 · J2SE · 非技术 · C · C++ · C# · Markdown

new ZipOutputStream(new FileOutputStream("c:/abc.txt"));

在操作文件或者流的时候最好不要这么写,因为这么写你无法在finally里面将流最终关闭,所以当您要删除文件的时候就会有IOException,最终导致文件无法删除!


public String compressionFiles() {
        ZipOutputStream zosm = null;
		FileOutputStream fosm = null;
		try {
			fosm = new FileOutputStream("c:/abc.txt");
			zosm = new ZipOutputStream(fosm);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (zosm != null) {
				zosm.close();
			}
			if (fosm != null) {
				fosm.close();
			}
		}
}

这样分开出来写,就可以保证所有的流最后都可以在finally中被正确关闭。

评论(6)

  1. #6 楼 · ylzyd12345 · 2011-12-30 23:19

    一般是先关闭输入流呢,还是先关闭输出流?

  2. #5 楼 · wolfbrood · 2009-02-15 09:51
    		}
    		if (fosm != null) {
    

    try { fosm.close(); }catch(IOException e) { //TODO: }

    		}
    

  3. #4 楼 · yourgame · 2009-02-15 01:59

    yourgame writes:

    现在是我在网上找的一个解压缩RAR文件的这样处理了也无济于事

    一般像流都有 close()方法,如果没有的情况下就 把变量设置为空。

  4. #3 楼 · yourgame · 2009-02-10 17:19

    huangleiatay writes:

    可以这么理解,ZipOutputStream 不会自动关闭它所包装的流

    ZipOutputStream这样处理了以后到没有问题了 现在是我在网上找的一个解压缩RAR文件的这样处理了也无济于事

  5. #2 楼 · 抛出异常的爱 · 2009-02-10 14:32

    用common.io这个包来写有关读文件与写文件的代码.

  6. #1 楼 · huangleiatay · 2009-02-10 11:09

    可以这么理解,ZipOutputStream 不会自动关闭它所包装的流

评论功能维护中,当前仅展示历史评论。