⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 downloadtest.java

📁 孙鑫JAVA从入门到精通配套练习程序。所有程序都实际运行过
💻 JAVA
字号:
//网络下载程序演示
import java.net.*;
import java.awt.event.*;
import javax.swing.*;

public class DownloadTest 
{
	public static void main(String[] args)
	{
		//用户界面编写
		JFrame f = new JFrame("Download Programming");
		f.setSize(600, 400);
		f.setLocation(300, 300);
		JPanel p = new JPanel();
		JLabel l = new JLabel("Input URL:");
		final JTextField tf = new JTextField(30);
		final JTextArea ta = new JTextArea();
		JButton btn = new JButton("Download");
		p.add(l);
		p.add(tf);
		f.getContentPane().add(p, "North");
		f.getContentPane().add(ta, "Center");
		f.getContentPane().add(btn, "South");
		//响应窗口关闭事件
		f.addWindowListener(new WindowAdapter()
		{
			public void windowClosing(WindowEvent e)
			{
				//System.out.println("exit now");
				System.exit(0);
			}
		});
		//响应下载按钮单击事件
		btn.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				try
				{
					//显示要下载内容的相关信息
					String str = tf.getText();
					URL url1 = new URL(str);
					URLConnection urlConn = url1.openConnection();
					String line = System.getProperty("line.separator");
					ta.append("Host: " + url1.getHost());
					ta.append(line);
					ta.append("Port: " + url1.getDefaultPort());
					ta.append(line);
					ta.append("ContentType: " + urlConn.getContentType());
					ta.append(line);
					ta.append("ContentLength: " + urlConn.getContentLength());
					//将下载的文件保存到当前目录下
					InputStream is = urlConn.getInputStream();
					FileOutputStream fos = new FileOutputStream("1.txt");
					//采用字节流方式下载,支持所有类型的文件
					int data;
					while((data=is.read()) != -1)
					{
						fos.write(data);
					}
					is.close();
					fos.close();
				}
				catch(Throwable ex)
				{
					System.out.println(ex);
				}
			}
		});
		f.show();
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -