gpt4 book ai didi

Java 通过套接字发送和接收文件

转载 作者:行者123 更新时间:2023-11-30 10:40:51 26 4
gpt4 key购买 nike

我目前正在尝试创建一个文件传输程序,该程序可以将文件从一个位置传输到另一个位置。该程序适用于 .txt 文件,但对于其他扩展名(例如 .exe),传输的文件无法正常打开。任何人都可以发现我的代码的问题吗?谢谢!

服务器代码:

import java.io.*;
import java.net.*;

public class SendFile{
static ServerSocket receiver = null;
static OutputStream out = null;
static Socket socket = null;
static File myFile = new File("C:\\Users\\hieptq\\Desktop\\AtomSetup.exe");
/*static int count;*/
static byte[] buffer = new byte[(int) myFile.length()];
public static void main(String[] args) throws IOException{
receiver = new ServerSocket(9099);
socket = receiver.accept();
System.out.println("Accepted connection from : " + socket);
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream in = new BufferedInputStream(fis);
in.read(buffer,0,buffer.length);
out = socket.getOutputStream();
System.out.println("Sending files");
out.write(buffer,0, buffer.length);
out.flush();
/*while ((count = in.read(buffer)) > 0){
out.write(buffer,0,count);
out.flush();
}*/
out.close();
in.close();
socket.close();
System.out.println("Finished sending");



}

}

客户端代码:

import java.io.*;
import java.net.*;

public class ReceiveFile{
static Socket socket = null;
static int maxsize = 999999999;
static int byteread;
static int current = 0;
public static void main(String[] args) throws FileNotFoundException, IOException{
byte[] buffer = new byte[maxsize];
Socket socket = new Socket("localhost", 9099);
InputStream is = socket.getInputStream();
File test = new File("D:\\AtomSetup.exe");
test.createNewFile();
FileOutputStream fos = new FileOutputStream(test);
BufferedOutputStream out = new BufferedOutputStream(fos);
byteread = is.read(buffer, 0, buffer.length);
current = byteread;

do{
byteread = is.read(buffer, 0, buffer.length - current);
if (byteread >= 0) current += byteread;
} while (byteread > -1);
out.write(buffer, 0, current);
out.flush();

socket.close();
fos.close();
is.close();

}
}

最佳答案

一个问题是您在从 InputStream 读取时覆盖了 buffer 的内容

    byteread = is.read(buffer, 0, buffer.length);
current = byteread;

do{
byteread = is.read(buffer, 0, buffer.length - current);
if (byteread >= 0) current += byteread;
} while (byteread > -1);

InputStream#read 将第二个参数声明为偏移量,它将存储在字节数组中,在您的情况下,偏移量始终为 0,因此它将在每次迭代中覆盖。

我建议简化从 InputStream 读取和写入 OutputStream 的逻辑

byte[] buffer = new byte[16384];

while ((byteread = is.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, byteread);
}

out.flush();

希望这对您有所帮助。

关于Java 通过套接字发送和接收文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38732970/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com