本文實例為大家分享了Java使用組件編寫窗口下載網上文件的具體代碼,供大家參考,具體內容如下
如圖
實現代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
package com.rain.get; import java.awt.*; import java.awt.event.*; import java.net.*; import java.io.*; import javax.swing.*; //從網絡取得文件 public class GetFileDemo extends JFrame{ JTextField jtfUrl; //輸入文件地址url JButton jbGetFile; //取文件按鈕 JLabel jlInfo; //顯示提示信息 public GetFileDemo(){ super ( "從網絡取得文件" ); //調用父類構造函數 Container container=getContentPane(); //得到容器 jtfUrl= new JTextField( 18 ); //實例化地址輸入框 jbGetFile= new JButton( "取文件" ); //實例化按鈕 jlInfo= new JLabel(); JPanel p= new JPanel(); //實例化一個面板,用于容納地址輸入框和取文件按鈕 p.add(jtfUrl); //增加組件到面板上 p.add(jbGetFile); container.add(p,BorderLayout.NORTH); //增加組件到容器上 container.add(jlInfo,BorderLayout.CENTER); jbGetFile.addActionListener( new ActionListener(){ //按鈕事件處理 public void actionPerformed(ActionEvent ent){ try { jlInfo.setText( "正在讀取" ); URL url= new URL(jtfUrl.getText()); //得到文件的URL地址 InputStream in=url.openStream(); //得到文件輸入流 String outFilename=JOptionPane.showInputDialog(GetFileDemo. this , "輸入保存文件名 " ); //輸入保存的文件名 FileOutputStream out= new FileOutputStream(outFilename); //得到文件輸出流 byte [] buffer= new byte [ 1024 ]; //緩沖區大小 int length; while ((length=in.read(buffer))!=- 1 ){ //讀取數據 out.write(buffer, 0 ,length); //寫入數據到文件 } out.close(); //關閉文件輸出流 in.close(); //關閉輸入流 jlInfo.setText( "讀取文件成功" ); //顯示提示信息 } catch (Exception ex){ ex.printStackTrace(); //輸出出錯信息 jlInfo.setText( "讀取文件失敗" ); } } }); setSize( 320 , 100 ); //設置窗口尺寸 setVisible( true ); //設置窗口可視 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //關閉窗口時退出程序 } public static void main(String[] args){ new GetFileDemo(); } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。