Java网络编程:如何实现文件传输

发布时间:2025-02-27 01:17:05 作者:小樊
来源:亿速云 阅读:114

在Java中,可以使用Socket和ServerSocket类来实现文件传输。以下是一个简单的示例,展示了如何使用这些类进行文件传输。

服务器

  1. 创建一个ServerSocket对象,监听指定端口。
  2. 接受客户端连接。
  3. 从客户端接收文件数据并写入到本地文件。
import java.io.*;
import java.net.*;

public class FileServer {
    public static void main(String[] args) {
        int port = 12345;
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("Server is listening on port " + port);
            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("New client connected");

                InputStream inputStream = socket.getInputStream();
                DataInputStream dataInputStream = new DataInputStream(inputStream);

                // Read file name and size from client
                String fileName = dataInputStream.readUTF();
                long fileSize = dataInputStream.readLong();

                // Write file to disk
                FileOutputStream fileOutputStream = new FileOutputStream(fileName);
                byte[] buffer = new byte[4096];
                int bytesRead;
                long totalBytesRead = 0;

                while (totalBytesRead < fileSize && (bytesRead = dataInputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, bytesRead);
                    totalBytesRead += bytesRead;
                }

                fileOutputStream.close();
                dataInputStream.close();
                socket.close();
                System.out.println("File received: " + fileName);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

客户端

  1. 创建一个Socket对象,连接到服务器。
  2. 从本地文件读取数据并发送给服务器。
import java.io.*;
import java.net.*;

public class FileClient {
    public static void main(String[] args) {
        String serverAddress = "localhost";
        int port = 12345;
        String filePath = "example.txt";

        try (Socket socket = new Socket(serverAddress, port)) {
            OutputStream outputStream = socket.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(outputStream);

            // Send file name and size to server
            File file = new File(filePath);
            dataOutputStream.writeUTF(file.getName());
            dataOutputStream.writeLong(file.length());

            // Read file and send to server
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                dataOutputStream.write(buffer, 0, bytesRead);
            }

            fileInputStream.close();
            dataOutputStream.close();
            socket.close();
            System.out.println("File sent: " + filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

运行步骤

  1. 先运行服务器端程序。
  2. 再运行客户端程序。

这样,客户端会将指定的文件发送到服务器,服务器接收到文件后将其保存到本地。

注意事项

  1. 这个示例没有处理异常情况,如文件不存在、网络中断等。
  2. 实际应用中,可能需要添加更多的功能,如进度显示、断点续传、多线程传输等。
  3. 为了安全起见,建议使用SSL/TLS来加密数据传输。
推荐阅读:
  1. java如何使用Pair实现成对结果的返回
  2. java如何实现简单音乐播放器

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:Java网络连接:如何管理连接池

下一篇:Java网络安全:如何防止数据泄露

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》