为什么小弟我下传后的文件无法从服务器删除

为什么我上传后的文件无法从服务器删除?
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中被正确关闭。


1 楼 huangleiatay 2009-02-10  
可以这么理解,ZipOutputStream 不会自动关闭它所包装的流
2 楼 抛出异常的爱 2009-02-10  
用common.io这个包来写有关读文件与写文件的代码.
3 楼 yourgame 2009-02-10  
huangleiatay 写道

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

ZipOutputStream这样处理了以后到没有问题了
现在是我在网上找的一个解压缩RAR文件的这样处理了也无济于事
4 楼 yourgame 2009-02-15  
yourgame 写道

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

一般像流都有 close()方法,如果没有的情况下就 把变量设置为空。
5 楼 wolfbrood 2009-02-15  
<div class="quote_title">yourgame 写道</div>
<div class="quote_div">
<pre name="code" class="java">new ZipOutputStream(new FileOutputStream("c:/abc.txt"));</pre>
<br />在操作文件或者流的时候最好不要这么写,因为这么写你无法在finally里面将流最终关闭,所以当您要删除文件的时候就会有IOException,最终导致文件无法删除!<br />
<pre name="code" class="java">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();
}
}
}
</pre>
<br />这样分开出来写,就可以保证所有的流最后都可以在finally中被正确关闭。<br /><br /><br /></div>
<p>//变成如下</p>
<pre name="code" class="java">if (zosm != null) {
trt {
zosm.close();
} catch(Exception e) {
  //TODO:
}

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

}
</pre>
<p> 这样就不会因为zosm异常而没有关闭fosm流。</p>
6 楼 ylzyd12345 2011-12-30  
一般是先关闭输入流呢,还是先关闭输出流?