如何能使这个程序提高性能?

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();
}
}

...全文
114 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
gemouzhi 2005-11-13
  • 打赏
  • 举报
回复
下载的文件多大?

你这带UI的程式明显应该开线程的。
little06 2005-11-13
  • 打赏
  • 举报
回复
用jb的调试模式
逐步跟踪,看看里面变量使用的内存量,
如果是Cpu使用率太高
那要改进具体算法
snowmansh 2005-11-13
  • 打赏
  • 举报
回复
lljkljl

62,626

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧