如何能使这个程序提高性能?
zjay 2005-11-13 06:46:51 一个简单的下载程序,但运行时占用了太多的系统资源,怎么改才能提高它的性能呢?代码如下
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class GUI extends Frame
{
Download dl ;
static URL url;
static URLConnection urlConn;
String str;
URL geturl(String str)throws Exception
{
return new URL(str);
}
void action(TextArea ta,TextField tf)throws Exception
{
dl = new Download(geturl(tf.getText()),geturl(tf.getText()).openConnection());
String line=System.getProperty("line.separator");
ta.append("主机: "+dl.getHost());
ta.append(line);
ta.append("端口: "+dl.getPort());
ta.append(line);
ta.append("文件类型: "+dl.getType());
ta.append(line);
ta.append("文件大小: "+dl.getLength());
dl.downLoad();
}
GUI()throws Exception
{
setTitle("下载程序");
setSize(600,400);
setLocation(100,100);
setBackground(Color.lightGray);
Panel p=new Panel();
Label l=new Label("请输入 URL:");
final TextField tf=new TextField(30);
final TextArea ta=new TextArea();
Button btn=new Button("下载");
p.add(l);
p.add(tf);
add(p,"North");
add(ta,"Center");
p.add(btn);
btn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
action(ta,tf);
}
catch(Exception ex)
{
ex.toString();
}
}
});
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
class Download
{
URL url;
URLConnection urlConn;
public String getFileName(URL url)
{
String fileName = url.getFile();
return fileName.substring(fileName.lastIndexOf('/') + 1);
}
public Download(URL url,URLConnection urlConn)
{
this.url = url;
this.urlConn = urlConn;
}
public void downLoad()
{
try
{
InputStream is=urlConn.getInputStream();
FileOutputStream fos=new FileOutputStream(getFileName(url));
int data;
while((data=is.read())!=-1)
{
fos.write(data);
}
is.close();
fos.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public String getHost()
{
return url.getHost();
}
public int getPort()
{
return url.getDefaultPort();
}
public String getType()
{
return urlConn.getContentType();
}
public int getLength()
{
return urlConn.getContentLength();
}
}
class test
{
public static void main(String[] args)throws Exception
{
GUI gui = new GUI();
gui.show();
}
}