Java通过套接字发送和接收文件(byte[])

我正在尝试开发一个非常简单的客户端/服务器,其中客户端将文件转换为字节,将其发送到服务器,然后将字节转换回文件。

当前,程序仅创建一个空文件。我不是一个出色的Java开发人员,因此不胜感激。

这是接收客户端发送的内容的服务器部分。

ServerSocket serverSocket = null;

serverSocket = new ServerSocket(4444);

Socket socket = null;

socket = serverSocket.accept();

DataOutputStream out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));

DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));

byte[] bytes = new byte[1024];

in.read(bytes);

System.out.println(bytes);

FileOutputStream fos = new FileOutputStream("C:\\test2.xml");

fos.write(bytes);

这是客户端部分

Socket socket = null;

DataOutputStream out = null;

DataInputStream in = null;

String host = "127.0.0.1";

socket = new Socket(host, 4444);

out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));

in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));

File file = new File("C:\\test.xml");

//InputStream is = new FileInputStream(file);

// Get the size of the file

long length = file.length();

if (length > Integer.MAX_VALUE) {

System.out.println("File is too large.");

}

byte[] bytes = new byte[(int) length];

//out.write(bytes);

System.out.println(bytes);

out.close();

in.close();

socket.close();

回答:

在Java中复制流的正确方法如下:

int count;

byte[] buffer = new byte[8192]; // or 4096, or more

while ((count = in.read(buffer)) > 0)

{

out.write(buffer, 0, count);

}

希望我每次在论坛上发布时都能获得一美元。

以上是 Java通过套接字发送和接收文件(byte[]) 的全部内容, 来源链接: utcz.com/qa/400929.html

回到顶部