日期:2014-05-20  浏览次数:20815 次

菜鸟一枚,求代码优化1拒绝灌水!
/*
需求:将一个Mp3文件分割成4个,然后在合并,并试着播放该合并后的文件;
思路:将该文件作为源读取,然后输出到目的文件中去,这是整体的思路
整个操作的都是字节流信息;类似于复制文件的操作
源:InputStream,Reader
是否为纯文本?否,InputStream,FileInputStream
设备:硬盘文件,是否要提高效率?是
最终选:BufferedInputStream 
目的:OutputStream,Writer
是否为纯文本?否 OutputStream,是否要提高效率?是
最终选择BufferedOutputStream
步骤:
*/
package splitmp3;
import java.io.*;
import java.util.*;
class SplitMp3
{
public static void main(String []args)
{
combineMp3();
}
public static void combineMp3()
{

Vector<FileInputStream> vec=new Vector<FileInputStream>();
try
{
for(int i=1;i!=5;i++)
vec.add(new FileInputStream(""+i+".part"));
}
catch(IOException ioe )
{
throw new RuntimeException("文件输入流打开失败。。。");
}
Enumeration<FileInputStream> em=vec.elements();
SequenceInputStream sis=null;
File file=new File("范玮琪 - 一个像夏天一个像秋天.mp3");
try
{
if(!file.exists())
file.createNewFile();
}
catch(IOException ioe)
{
throw new RuntimeException("mp3文件创建失败。。。");
}
BufferedOutputStream bos=null;
try
{
sis=new SequenceInputStream(em);
bos=new BufferedOutputStream(new FileOutputStream(file));
byte[]buf=new byte[1024*1024];
int len=0;
while((len=sis.read(buf))!=-1)
{
bos.write(buf,0,len);
}
}
catch(IOException ioe)
{
throw new RuntimeException("读文件流链打开失败");
}
finally
{
try
{
if(bos!=null)
bos.close();
}
catch(IOException ioe)
{
throw new RuntimeException("写文件输出流关闭失败");
}

try
{
if(sis!=null)
sis.close();
}
catch(IOException ioe)
{
throw new RuntimeException("读文件输入流链关闭失败");
}

}


}
public static void splitMp3()
{
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
try
{
bis=new BufferedInputStream(new FileInputStream("E:\\Kugou\\KuGou\\范玮琪 - 一个像夏天一个像秋天.mp3"));
int len=0;
byte[]buf=new byte[1024*1024];
int count=1;
while((len=bis.read(buf))!=-1)
{
bos=new BufferedOutputStream(new FileOutputStream(""+(count++)+".part"));
bos.write(buf,0,len);
}
}
catch(IOException ioe)
{
throw new RuntimeException("读写文件失败。。。");
}
finally
{
try
{
if(bis!=null)
bis.close();
}
catch(IOException ioe)
{
throw new RuntimeException("读文件关闭异常。。。。");
}
try
{
if(bis!=null)
bis.close();
}
catch(IOException ioe)
{
throw new RuntimeException("写文件关闭异常。。。。");
}
}
}
}
如此多的RuntimeException,该怎么优化,有什么解决方案么?代码运行没问题的。。

------解决方案--------------------
推荐不要优化,因为你优化了以后就无法准确的知道异常是在哪个地方抛出的了,如果出错你也就不好调错了。
推荐优化的也就关闭资源的两个try{}catch而已,但是基本算是没优化。

Java code

try
{
if(bis!=null){
bis.close();
}

if(bis!=null){
bis.close();
}
}
catch(IOException ioe)
{
throw new RuntimeException("关闭资源失败。。。。");
}

------解决方案--------------------
意思是说:如果你并不能有效处理该异常,也没有什么好处理的,就没必要将其转为运行时异常,因为运行时异常不是显式声明的,外面的调用者就无法预期这种异常了。

而有时候是需要的,比如某些时候发生异常:需要回滚事务,记录详细的日志等。


不需要重复包装的意思就是,没必要把原有的异常又换个方式抛出去,这隐藏了有价值的信息。
本来异常时IOException,一看名字都知道,是IO操作问题,你换成RuntimeException,看了名字也完全不知道是怎么回事。