修改后的代码如下:

package ftp;

import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.net.Socket; import java.util.Scanner;

/**

  • 文件传输Client端
    */ public class FileTransferClient extends Socket {

    private static final String SERVER_IP = "10.41.104.38"; // 服务端IP private static final int SERVER_PORT = 8899; // 服务端端口

    private Socket client;

    private FileInputStream fis;

    private DataOutputStream dos;

    /**

    • 构造函数
    • 与服务器建立连接
    • @throws Exception */ public FileTransferClient() throws Exception { super(SERVER_IP, SERVER_PORT); this.client = this; System.out.println("Cliect[port:" + client.getLocalPort() + "] 成功连接服务端"); }

    /**

    • 向服务端传输文件

    • @throws Exception */ public void sendFile() throws Exception { Scanner scanner = new Scanner(System.in); System.out.println("请输入文件路径:"); String filePath = scanner.nextLine(); try { File file = new File(filePath); if (file.exists()) { fis = new FileInputStream(file); dos = new DataOutputStream(client.getOutputStream());

           // 文件名和长度
           dos.writeUTF(file.getName());
           dos.flush();
           dos.writeLong(file.length());
           dos.flush();
      
           // 开始传输文件
           System.out.println("======== 开始传输文件 ========");
           byte[] bytes = new byte[1024];
           int length = 0;
           long progress = 0;
           while ((length = fis.read(bytes, 0, bytes.length)) != -1) {
               dos.write(bytes, 0, length);
               dos.flush();
               progress += length;
               System.out.print("| " + (100 * progress / file.length()) + "% |");
           }
           System.out.println();
           System.out.println("======== 文件传输成功 ========");
       }
      

      } catch (Exception e) { e.printStackTrace(); } finally { scanner.close(); if (fis != null) fis.close(); if (dos != null) dos.close(); client.close(); } }

    /**

    • 入口
    • @param args */ public static void main(String[] args) { try { FileTransferClient client = new FileTransferClient(); // 启动客户端连接 client.sendFile(); // 传输文件 } catch (Exception e) { e.printStackTrace(); } }

}

修改内容:

  1. 在sendFile()方法中增加交互式输入文件路径的功能,使用Scanner类实现。

  2. 在finally块中关闭Scanner对象。

这样修改后,用户可以在命令行中输入文件路径,而不是在代码中写死文件路径。增加了程序的灵活性和易用性

修改下列代码增加交互页面:package ftp;import javaioDataOutputStream;import javaioFile;import javaioFileInputStream;import javanetSocket; 文件传输Client端br public class FileTransferClient extends Socket private st

原文地址: http://www.cveoy.top/t/topic/flVm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录