您好,登錄后才能下訂單哦!
利用java 怎么在局域網中進行文件傳輸?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
java 實現局域網文件傳輸
ClientFile.java
/** * 更多資料歡迎瀏覽凱哥學堂官網:http://kaige123.com * @author 小沫 */ package com.tcp.file; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; import javax.swing.JProgressBar; public class ClientFile extends Thread { private static String ip; private static int port; private String filepath; private long size; private JProgressBar jprogressbar; public ClientFile(String ip, int port, String filepath, JProgressBar jprogressbar) { this.ip = ip; this.port = port; this.filepath = filepath; this.jprogressbar = jprogressbar; } public void run() { try { Socket socket = new Socket(ip, port); InputStream input = socket.getInputStream(); OutputStream output = socket.getOutputStream(); File file = new File(filepath); // 第一次傳輸文件名字and文件的大小 String str1 = file.getName() + "\t" + file.length(); output.write(str1.getBytes()); output.flush(); byte[] b = new byte[100]; int len = input.read(b); String s = new String(b, 0, len); // 如果服務器傳輸過來的是ok那么就開始傳輸字節 if (s.equalsIgnoreCase("ok")) { long size = 0; jprogressbar.setMaximum((int) (file.length() / 10000));// 設置進度條最大值 FileInputStream fin = new FileInputStream(file); byte[] b1 = new byte[1024 * 1024 * 2]; while (fin.available() != 0) { len = fin.read(b1); output.write(b1, 0, len); output.flush(); size += len; jprogressbar.setValue((int) (size / 10000)); } if (fin.available() == 0) { javax.swing.JOptionPane.showMessageDialog(null, "傳輸完畢!即將推出......"); try { Thread.sleep(1500); System.exit(0); } catch (InterruptedException e) { e.printStackTrace(); } } output.close(); fin.close(); socket.close(); } else { // 傳輸的不是ok那么就彈出個信息框對方拒絕 javax.swing.JOptionPane.showMessageDialog(null, "對方拒絕接收此數據!"); } } catch (IOException e) { javax.swing.JOptionPane.showMessageDialog(null, "IOException"); } } }
ServerFile.java
/** * 更多資料歡迎瀏覽凱哥學堂官網:http://kaige123.com * @author 小沫 */ package com.tcp.file; import java.io.*; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.JProgressBar; public class ServerFile extends Thread { private Socket socket; private JProgressBar jprogressbars; public ServerFile(Socket socket, JProgressBar jprogressbars) { this.socket = socket; this.jprogressbars = jprogressbars; } public void run() { try { InputStream input = socket.getInputStream(); OutputStream output = socket.getOutputStream(); byte[] b = new byte[100]; int len = input.read(b); String ss = new String(b, 0, len); String[] str1 = ss.split("\t");// 把接收到的信息按制表符拆分 String filename = str1[0];// 起始位文件名稱 String filesize = str1[1];// 下標1位文件的大小 long size = Long.parseLong(filesize); InetAddress ip = socket.getInetAddress();// 得到發送端的IP int port = socket.getPort();// 得到發送端的端口 long s = size / 1024 / 1024; String name = " M"; if (s < 1) { s = (size / 1024); name = " K"; } else if (s > 1024) { float s1 = size / 1024 / 1024; s = (size / 1024 / 1024 / 1024); name = " G多"; } // 彈出確認款,顯示對方的ip端口以及文件的名稱和大小是否需要接收 int i = JOptionPane.showConfirmDialog(null, "來自: " + ip + ":" + port + "\n文件名稱: " + filename + "\n文件大小: " + s + name); // 如果點擊確認 if (i == JOptionPane.OK_OPTION) { // 那么傳輸ok給發送端示意可以接收 output.write("ok".getBytes()); output.flush(); JFileChooser jf = new JFileChooser(); // 存儲到本地路徑的夾子 jf.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); jf.showOpenDialog(null); jprogressbars.setMaximum((int) (size / 10000)); FileOutputStream fout = new FileOutputStream(new File(jf.getSelectedFile(), filename)); b = new byte[1024 * 1024 * 2]; long size1 = 0; while ((len = input.read(b)) != -1) { fout.write(b, 0, len); size1 += len; jprogressbars.setValue((int) (size1 / 10000)); } fout.close(); input.close(); socket.close(); } else { // 否不接收此文件 output.write("no".getBytes()); output.flush(); } } catch (IOException e) { javax.swing.JOptionPane.showMessageDialog(null, "IOException"); } } private static ServerSocket server = null; // 啟動服務器 public static void openServer(int port, JProgressBar jprogressbar) throws Exception { new Thread() { public void run() { try { if (server != null && !server.isClosed()) { server.close(); } server = new ServerSocket(port); new ServerFile(server.accept(), jprogressbar).start(); } catch (IOException e) { javax.swing.JOptionPane.showMessageDialog(null, "IOException"); } } }.start(); } // 關閉服務器 public static void closeServer() { try { server.close(); } catch (IOException e) { javax.swing.JOptionPane.showMessageDialog(null, "IOException"); } } }
SocketFileJFrame.java
/** * 更多資料歡迎瀏覽凱哥學堂官網:http://kaige123.com * @author 小沫 */ package com.tcp.file; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Image; import java.awt.Toolkit; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import java.awt.Color; import javax.swing.JTabbedPane; import java.awt.Panel; import javax.swing.border.TitledBorder; import javax.swing.UIManager; import javax.swing.border.CompoundBorder; import javax.swing.JLabel; import java.awt.Font; import javax.swing.JTextField; import javax.swing.JToggleButton; import javax.swing.JProgressBar; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.event.AncestorListener; import javax.swing.event.AncestorEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.awt.event.ActionEvent; public class SocketFileJFrame extends JFrame { private JPanel contentPane; private JTextField textField; private JTextField textField_1; private JTextField textField_2; private JTextField textField_3; private JProgressBar progressBar_2; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { SocketFileJFrame frame = new SocketFileJFrame(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public SocketFileJFrame() { setIconImage(Toolkit.getDefaultToolkit() .getImage(SocketFileJFrame.class.getResource("/javax/swing/plaf/metal/icons/ocean/newFolder.gif"))); setForeground(Color.WHITE); setResizable(false); setTitle("局域網文件傳輸 V1.0"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); int width = Toolkit.getDefaultToolkit().getScreenSize().width;//獲取分辨率寬 int heiht = Toolkit.getDefaultToolkit().getScreenSize().height;//獲取分辨率高 //分辨率寬高減去軟件的寬高除以2把軟件居中顯示 setBounds((width - 747) / 2, (heiht - 448) / 2, 738, 472); contentPane = new JPanel(); contentPane.setBackground(Color.WHITE); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JPanel panel_1 = new JPanel(); panel_1.setToolTipText(""); panel_1.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "\u6587\u4EF6\u63A5\u6536\u670D\u52A1\u5668", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0))); panel_1.setBackground(Color.WHITE); panel_1.setBounds(39, 28, 652, 119); contentPane.add(panel_1); panel_1.setLayout(null); JLabel label = new JLabel("\u7AEF\u53E3:"); label.setFont(new Font("新宋體", Font.PLAIN, 22)); label.setBounds(26, 31, 66, 35); panel_1.add(label); //端口文本框 textField = new JTextField(); textField.setFont(new Font("宋體", Font.PLAIN, 19)); textField.setText("8080"); textField.setBounds(89, 36, 126, 26); panel_1.add(textField); textField.setColumns(10); //服務器關閉啟動的按鈕 JToggleButton tglbtnNewToggleButton = new JToggleButton("\u542F\u52A8\u670D\u52A1\u5668"); tglbtnNewToggleButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (tglbtnNewToggleButton.isSelected()) { //如果是按下顯示關閉服務器 tglbtnNewToggleButton.setText("關閉服務器"); textField.setEnabled(false);//按下之后 端口文本框要設置不能寫入 try { //啟動服務器 ServerFile.openServer(Integer.parseInt(textField.getText()) , progressBar_2); } catch (Exception e1) { javax.swing.JOptionPane.showMessageDialog(null, "Exception"); } } else { //否啟動服務器 tglbtnNewToggleButton.setText("啟動服務器"); textField.setEnabled(true);////彈起之后 端口文本框要設置可寫狀態 ServerFile.closeServer();//關閉服務器 } } }); tglbtnNewToggleButton.setFont(new Font("微軟雅黑 Light", Font.PLAIN, 19)); tglbtnNewToggleButton.setBackground(Color.WHITE); tglbtnNewToggleButton.setForeground(Color.DARK_GRAY); tglbtnNewToggleButton.setBounds(345, 34, 138, 28); panel_1.add(tglbtnNewToggleButton); //文件接收端的進度條 progressBar_2 = new JProgressBar(); progressBar_2.setBackground(Color.WHITE); progressBar_2.setForeground(new Color(255, 218, 185)); progressBar_2.setStringPainted(true); progressBar_2.setBounds(460, 101, 190, 14); panel_1.add(progressBar_2); JPanel panel_2 = new JPanel(); panel_2.setToolTipText(""); panel_2.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "\u6587\u4EF6\u4F20\u8F93\u7AEF", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0))); panel_2.setBackground(Color.WHITE); panel_2.setBounds(39, 191, 652, 202); contentPane.add(panel_2); panel_2.setLayout(null); //文件傳輸端的進度條 JProgressBar progressBar_1 = new JProgressBar(); progressBar_1.setFont(new Font("宋體", Font.PLAIN, 18)); progressBar_1.setStringPainted(true); progressBar_1.setForeground(new Color(240, 128, 128)); progressBar_1.setBackground(Color.WHITE); progressBar_1.setBounds(96, 169, 472, 20); panel_2.add(progressBar_1); JLabel lblIp = new JLabel("IP\u5730\u5740:"); lblIp.setFont(new Font("微軟雅黑 Light", Font.PLAIN, 20)); lblIp.setBounds(26, 44, 70, 27); panel_2.add(lblIp); //IP地址文本框 textField_1 = new JTextField(); textField_1.setText("127.0.0.1"); textField_1.setFont(new Font("新宋體", Font.PLAIN, 20)); textField_1.setBounds(96, 44, 184, 30); panel_2.add(textField_1); textField_1.setColumns(10); JLabel label_1 = new JLabel("\u7AEF\u53E3:"); label_1.setFont(new Font("微軟雅黑 Light", Font.PLAIN, 20)); label_1.setBounds(308, 42, 80, 30); panel_2.add(label_1); //端口文本框 textField_2 = new JTextField(); textField_2.setText("8080"); textField_2.setFont(new Font("新宋體", Font.PLAIN, 20)); textField_2.setColumns(10); textField_2.setBounds(359, 44, 80, 30); panel_2.add(textField_2); //打開本地路徑的按鈕 JButton button = new JButton("..."); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser jf = new JFileChooser(); jf.setFileSelectionMode(JFileChooser.FILES_ONLY); jf.showOpenDialog(SocketFileJFrame.this); textField_3.setText(jf.getSelectedFile().getPath()); } }); button.setBackground(Color.WHITE); button.setBounds(533, 51, 35, 20); panel_2.add(button); JLabel label_2 = new JLabel("\u8DEF\u5F84:"); label_2.setFont(new Font("微軟雅黑 Light", Font.PLAIN, 15)); label_2.setBounds(489, 50, 44, 18); panel_2.add(label_2); //顯示文件路徑框 textField_3 = new JTextField(); textField_3.setEnabled(false); textField_3.setFont(new Font("微軟雅黑 Light", Font.PLAIN, 20)); textField_3.setBounds(96, 100, 343, 38); panel_2.add(textField_3); textField_3.setColumns(10); JLabel lblNewLabel = new JLabel("\u6587\u4EF6:"); lblNewLabel.setFont(new Font("等線 Light", Font.PLAIN, 25)); lblNewLabel.setBounds(33, 97, 56, 38); panel_2.add(lblNewLabel); //確定按鈕 JButton button_1 = new JButton("\u786E\u5B9A"); button_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ClientFile client = new ClientFile( textField_1.getText(), Integer.parseInt(textField_2.getText()), textField_3.getText(), progressBar_1); client.start(); } }); button_1.setForeground(new Color(255, 255, 0)); button_1.setBackground(new Color(233, 150, 122)); button_1.setFont(new Font("微軟雅黑 Light", Font.BOLD, 20)); button_1.setBounds(475, 100, 91, 38); panel_2.add(button_1); } }
看完上述內容,你們掌握利用java 怎么在局域網中進行文件傳輸的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。