Java文件传输(有进度条)

Tcp连接实现文件传输,使用ServcerScoket与Scoket类实现服务器与客户端建立连接
	
考虑美观问题用idea的JfromDeSigener设计界面,虽然也不怎么美观...

客户端

文件选择部分

private void selectFileMouseClicked(MouseEvent e) {
        // TODO add your code here
        JFileChooser jFileChooser = new JFileChooser();//创建文件选择器
        jFileChooser.showOpenDialog(this);//显示文件打开框
        if(jFileChooser.getSelectedFile() != null)//选择了文件
        {
            file = jFileChooser.getSelectedFile();
            filemess.setText("");//清空之前显示的文件名
            filemess.setText(file.getName());
        }

    }

文件传输部分

整的比较花里胡哨,加了个服务端接收拒绝的功能
		
		upprobar.setString(null);//设置进度条内容为空
        upprobar.setStringPainted(true);//设置进度条显示百分比
        //获取ip地址
        String ip = ip_text.getText().trim();
        //获取端口号
        String port_str = port_text.getText().trim();
        int port = 0;
        
        if(port_str != null && (!("".equals(port_str)))){
            port = Integer.parseInt(port_str);
            System.out.println(port);
        }
        if(ip != null && port != 0 && !("".equals(ip))) {
            try {
                //创建socket
                socket = new Socket(ip,port);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    FileUp();
                }
            }).start();
        }else {
            JOptionPane.showMessageDialog(this,"请输入IP地址或端口号");
        }


private void FileUp() {
        double percentage = 0;//百分比
        OutputStream outputStream = null;
        FileInputStream fileInputStream = null;
        DataOutputStream dataOutputStream = null;
        try {
            long AllSize = file.length();//获取文件的大小,单位字节
            outputStream = socket.getOutputStream();
            fileInputStream = new FileInputStream(file);
            DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
            dataOutputStream = new DataOutputStream(socket.getOutputStream());
            String receflag = dataInputStream.readUTF();
            if("接收".equals(receflag)){
                long read_size = 0;
                byte[] filebuffeer = new byte[1024];
                int len = 0;//每次上传的大小
                //发送文件名
                dataOutputStream.writeUTF(file.getName());
                //发送文件大小
                dataOutputStream.writeLong(AllSize);
                while((len = fileInputStream.read(filebuffeer)) != -1){
                    read_size += len;//计算当前传输的总字节数
                    outputStream.write(filebuffeer,0,len);
                    outputStream.flush();
                    percentage = (double) read_size / AllSize;//计算当前传输进度
                    upprobar.setValue((int) (percentage * 100));
                }
                upprobar.setString("上传完成");
            }else if("拒绝接收".equals(receflag)){
                JOptionPane.showMessageDialog(this,"服务端拒绝接收");
            }
            System.out.println(socket);
            // fileInputStream.close();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        finally {
            if(fileInputStream != null){
                try {
                    fileInputStream.close();
                    System.out.println("文件输入流关闭");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream != null){
                try {
                    outputStream.close();
                    System.out.println("输出流关闭");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(dataOutputStream != null){
                try {
                    dataOutputStream.close();
                    System.out.println("数据输出流关闭");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
     }

服务端

比较简陋,凑合看吧,又不是不能用,哈哈

在这里插入图片描述

 private void Receive_File() {
        Socket socket = null;
        InputStream inputStream = null;
        DataInputStream dataInputStream = null;
        FileOutputStream fileOutputStream = null;
        DataOutputStream dataOutputStream = null;
        try {
            socket = serverSocket.accept();
            System.out.println("有新客户端接入");
            dataOutputStream = new DataOutputStream(socket.getOutputStream());
            int rece_flag = JOptionPane.showConfirmDialog(this,"有新文件,是否接受文件","",JOptionPane.YES_NO_OPTION);
            if(rece_flag == 0){
                JFileChooser jFileChooser = new JFileChooser();//创建文件选择器
                jFileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);//可以选择文件与文件夹
                int saveflag =  jFileChooser.showSaveDialog(this);//显示文件保存对话框
                if(saveflag == JFileChooser.APPROVE_OPTION) {
                    dataOutputStream.writeUTF("接收");
                    String filepath = jFileChooser.getSelectedFile().getAbsolutePath();
                    inputStream = socket.getInputStream();
                    dataInputStream = new DataInputStream(socket.getInputStream());
                    down_pro.setString(null);
                    down_pro.setStringPainted(true);
                    File file = new File(filepath + dataInputStream.readUTF());//通过选择的文件路径+传输的文件名,确定文件保存位置
                    fileOutputStream  = new FileOutputStream(file);
                    long read_size = 0;
                    double percentage = 0;//百分比
                    long filesize = dataInputStream.readLong();//获取文件大小
                    int len = 0;//每次接收的大小
                    byte[] bytes = new byte[1024];
                    //下边这部分,基本跟客户端一样
                    while((len = inputStream.read(bytes)) != -1){
                        read_size += len;
                        fileOutputStream.write(bytes,0,len);
                        fileOutputStream.flush();
                        percentage = (double) read_size / filesize;
                        down_pro.setValue((int)(percentage * 100));
                        // System.out.println((int)(percentage * 100));
                        if(read_size == filesize){
                            JOptionPane.showMessageDialog(this,"接收完成");
                        }
                    }
                    down_pro.setString("接收完成");
                }

            }else if(rece_flag == 1){
                dataOutputStream.writeUTF("拒绝接收");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
           if(fileOutputStream != null){
               try {
                   fileOutputStream.close();
                   System.out.println("文件输出流关闭");
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
            if(inputStream != null){
                try {
                    inputStream.close();
                    System.out.println("输入流关闭");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(dataInputStream != null){
                try {
                    dataInputStream.close();
                    System.out.println("数据输入流关闭");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(socket != null){
                try {
                    socket.close();
                    System.out.println("socket关闭");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Java Swing组件库中的JProgressBar来实现上传文件进度条。具体实现步骤如下: 1. 创建一个JProgressBar对象,并将其添加到Swing窗口中。 2. 在上传文件时,通过监听上传的进度来更新JProgressBar的值。 3. 当上传完成后,将JProgressBar的值设置为100%。 下面是一个简单的实现示例: ```java import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; public class UploadFile extends JFrame implements ActionListener { private JProgressBar progressBar; public UploadFile() { super("上传文件"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); getContentPane().setLayout(new BorderLayout()); // 创建进度条并添加到窗口中 progressBar = new JProgressBar(0, 100); progressBar.setStringPainted(true); getContentPane().add(progressBar, BorderLayout.CENTER); // 添加上传文件按钮 JButton uploadButton = new JButton("上传文件"); uploadButton.setActionCommand("upload"); uploadButton.addActionListener(this); getContentPane().add(uploadButton, BorderLayout.SOUTH); pack(); setLocationRelativeTo(null); } public void actionPerformed(ActionEvent e) { if ("upload".equals(e.getActionCommand())) { // 弹出文件选择对话框选择要上传的文件 JFileChooser fileChooser = new JFileChooser(); int result = fileChooser.showOpenDialog(this); if (result == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); uploadFile(file); } } } private void uploadFile(File file) { try { // 模拟上传文件的过程 FileInputStream fis = new FileInputStream(file); long fileSize = file.length(); byte[] buffer = new byte[1024]; int bytesRead = 0; long totalBytesRead = 0; while ((bytesRead = fis.read(buffer)) != -1) { // 更新进度条的值 totalBytesRead += bytesRead; int progress = (int) (totalBytesRead * 100 / fileSize); progressBar.setValue(progress); } fis.close(); // 上传完成,将进度条的值设置为100% progressBar.setValue(100); JOptionPane.showMessageDialog(this, "上传完成!"); } catch (IOException e) { JOptionPane.showMessageDialog(this, "上传失败:" + e.getMessage()); } } public static void main(String[] args) { UploadFile uploadFile = new UploadFile(); uploadFile.setVisible(true); } } ``` 在这个示例中,我们使用了JProgressBar来显示上传文件进度,并通过模拟上传文件的过程来更新进度条的值。当上传完成后,我们将进度条的值设置为100%并弹出一个消息框来通知用户上传完成。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值