web文件下载
package download.util;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class DownLoadJFrame extends JFrame {
// 声明组件
private JLabel downLoadJLable;
private JTextField downLoadJTextField;
private JButton downLoadJButton;
public DownLoadJFrame() {
// 设置标题
super("下载工具");
// 设置大小
this.setSize(450, 300);
// 设置居中显示
this.setLocationRelativeTo(null);
// 设置窗体关闭即退出程序
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 获取容器对象
Container c = this.getContentPane();
// 设置容器面板布局为null
c.setLayout(null);
// 实例化组件
downLoadJLable = new JLabel("下载的地址:");
downLoadJTextField = new JTextField(
"http://172.22.64.103:8080/day01/images/3.jpg");
downLoadJButton = new JButton("下载");
// 设置组件的位置
downLoadJLable.setBounds(10, 20, 80, 30);
downLoadJTextField.setBounds(95, 20, 280, 30);
downLoadJButton.setBounds(120, 100, 100, 30);
// 添加到面板中
c.add(downLoadJLable);
c.add(downLoadJTextField);
c.add(downLoadJButton);
// 添加点击事件
downLoadJButton.addActionListener(new MyActionLis());
// 设置窗体可见
this.setVisible(true);
}
public static void main(String[] args) {
new DownLoadJFrame();
}
/**
* 内部类
*
* @author XinFei
*
*/
class MyActionLis implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
downLoadJButton.setEnabled(false);
System.out.println("bbbb");
try {
// 创建连接的URL对象
URL url = new URL(downLoadJTextField.getText());
// 打开连接
HttpURLConnection urlConn = (HttpURLConnection) url
.openConnection();
// 获取输入流对象
InputStream is = urlConn.getInputStream();
// 写出的文件
File file = new File("F:\\ss.jpg");
// 输出流对象
OutputStream os = new FileOutputStream(file);
int len = 0;
byte buffer[] = new byte[1023];
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
is.close();
os.flush();
os.close();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
882

被折叠的 条评论
为什么被折叠?



