1
本程序主要实现在本机上搜素文件并下载下来。
2
程序运行后,显示如下:
Host:127.0.0.1
Port:80
ContentType:null
ContentLength:-1
ContentType为空,不知为什么。。。???
3
源程序如下:
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.event.*;
public class download {
public static void main(String[] args)
{
JFrame jf=new JFrame("hp下载程序");
jf.setSize(600,400);
jf.setLocation(100,100);
JPanel p=new JPanel();
JLabel l=new JLabel("Please input URL:");
final JTextField tf=new JTextField(30);
p.add(l);
p.add(tf);
jf.getContentPane().add(p,"North");
final JTextArea ta=new JTextArea();
jf.getContentPane().add(ta,"Center");
JButton btn=new JButton("DOWNLOAD");
jf.getContentPane().add(btn,"South");
btn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String str=tf.getText();
try
{
URL url=new URL(str);
URLConnection urlConn=url.openConnection();
String line=System.getProperty("line.separator");
ta.append("Host:"+url.getHost());
ta.append(line);
ta.append("Port:"+url.getDefaultPort());
ta.append(line);
System.out.print(urlConn);
ta.append("ContentType:"+urlConn.getContentType());
ta.append(line);
ta.append("ContentLength:"+urlConn.getContentLength());
InputStream is=urlConn.getInputStream();
FileOutputStream fos=new FileOutputStream("1.html");
int data;
while((data=is.read())!=-1)
{
fos.write(data);
}
is.close();
fos.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
});
jf.addWindowListener(new WindowListener()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
public void windowOpened(WindowEvent arg0) {
// TODO Auto-generated method stub
}
public void windowClosed(WindowEvent arg0) {
// TODO Auto-generated method stub
}
public void windowIconified(WindowEvent arg0) {
// TODO Auto-generated method stub
}
public void windowDeiconified(WindowEvent arg0) {
// TODO Auto-generated method stub
}
public void windowActivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
public void windowDeactivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
});
jf.show();
}
}