论坛首页 入门技术论坛

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

浏览 2784 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-02-08   最后修改:2009-02-08
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中被正确关闭。


   发表时间:2009-02-10   最后修改:2009-02-10
可以这么理解,ZipOutputStream 不会自动关闭它所包装的流
0 请登录后投票
   发表时间:2009-02-10  
用common.io这个包来写有关读文件与写文件的代码.
0 请登录后投票
   发表时间:2009-02-10  
huangleiatay 写道

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

ZipOutputStream这样处理了以后到没有问题了
现在是我在网上找的一个解压缩RAR文件的这样处理了也无济于事
0 请登录后投票
   发表时间:2009-02-15  
yourgame 写道

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

一般像流都有 close()方法,如果没有的情况下就 把变量设置为空。
0 请登录后投票
   发表时间:2009-02-15  
yourgame 写道
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中被正确关闭。


//变成如下

if (zosm != null) {
trt {
				zosm.close();
} catch(Exception e) {
  //TODO:
}

			}
			if (fosm != null) {
  try {
				fosm.close();
}catch(IOException e) {
  //TODO:
}

			}

 这样就不会因为zosm异常而没有关闭fosm流。

0 请登录后投票
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics