java使用套接字发送文件 [英] java send file using sockets

查看:99
本文介绍了java使用套接字发送文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Java将文件从一台计算机发送到另一台计算机。我已经编写了下面的代码,如果发送方和接收方都在同一台计算机上启动,但如果它们在不同的机器上工作,则接收文件大小比原始文件大,并且它已损坏,它可以正常工作。

I am trying to send a file from one computer to another using Java. I have written the code below, it works fine if both sender and receiver are started in the same computer but if they work on different machines received file size is bigger than the original file and it is corrupted.

注意:我正在尝试传输最多10 MB的文件。

Note: I am trying to transfer files which are max 10 MBs.

我该如何解决这个问题?

How can I fix this?

发件人:

ServerSocket server_socket = new ServerSocket(8989);
File myFile = new File(myPath);

Socket socket = server_socket.accept();
int count;
byte[] buffer = new byte[1024];

OutputStream out = socket.getOutputStream();
BufferedInputStream in = new BufferedInputStream(new FileInputStream(myFile));
while ((count = in.read(buffer)) > 0) {
     out.write(buffer, 0, count);
     out.flush();
}
socket.close();

接收方:

Socket socket = new Socket(address, 8989);
FileOutputStream fos = new FileOutputStream(anotherPath);
BufferedOutputStream out = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024];
int count;
InputStream in = socket.getInputStream();
while((count=in.read(buffer)) >0){
    fos.write(buffer);
}
fos.close();
socket.close();


推荐答案

在客户端,你写 计算字节并发送:

On the client side you write up to count bytes and send them:

while ((count = in.read(buffer)) > 0) {
  out.write(buffer, 0, count);

服务器端的

您阅读 count bytes - 但是你将整个缓冲区写入文件!

on the server side you read up to count bytes - but then you write the whole buffer to file!

while((count=in.read(buffer)) > 0){
  fos.write(buffer);

只需将其更改为:

fos.write(buffer, 0, count);

你会安全的。 BTW你的程序有另一个小bug: read()可以返回 0 这并不意味着 InputStream 已结束。请改为使用> =

and you'll be on the safe side. BTW your program has another small bug: read() can return 0 which doesn't mean InputStream ended. Use >= instead:

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






您是否考虑过< a href =http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html#copy(java.io.InputStream,%20java.io.OutputStream) =来自Apache Commons的noreferrer> IOUtils.copy(InputStream,OutputStream) ?这将减少你的整个,而循环到:

OutputStream out = socket.getOutputStream();
InputStream in = new FileInputStream(myFile);
IOUtils.copy(in, out);
socket.close();

写入的代码减少,测试代码减少。缓冲是在内部完成的。

Less code to write, less code to test. And buffering is done internally.

这篇关于java使用套接字发送文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆