gpt4 book ai didi

java - 发送文件名,然后发送文件本身

转载 作者:行者123 更新时间:2023-12-02 00:20:54 26 4
gpt4 key购买 nike

我想让我的服务器能够获取将发送给它的文件的名称,然后在获取该文件后,它可以使用正确的名称将其保存在新位置。

这是服务器代码:

class TheServer {

public void setUp() throws IOException { // this method is called from Main class.
ServerSocket serverSocket = new ServerSocket(1991);
System.out.println("Server setup and listening...");
Socket connection = serverSocket.accept();
System.out.println("Client connect");
System.out.println("Socket is closed = " + serverSocket.isClosed());



BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));

String str = rd.readLine();
System.out.println("Recieved: " + str);
rd.close();



InputStream is = connection.getInputStream();

int bufferSize = connection.getReceiveBufferSize();

FileOutputStream fos = new FileOutputStream("C:/" + str);
BufferedOutputStream bos = new BufferedOutputStream(fos);


byte[] bytes = new byte[bufferSize];

int count;

while ((count = is.read(bytes)) > 0) {
bos.write(bytes, 0, count);
}

bos.flush();
bos.close();
is.close();
connection.close();
serverSocket.close();


}
}

这是客户端代码:

public class TheClient {

public void send(File file) throws UnknownHostException, IOException { // this method is called from Main class.
Socket socket = null;
String host = "127.0.0.1";

socket = new Socket(host, 1991);

// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
System.out.println("File is too large.");
}

BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
wr.write(file.getName());
wr.flush();

byte[] bytes = new byte[(int) length];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());

int count;

while ((count = bis.read(bytes)) > 0) {
out.write(bytes, 0, count);
}


out.flush();
out.close();
fis.close();
bis.close();
socket.close();
}
}

我自己做了一些测试,看来我的客户端发送的文件名是正确的,但不知何故服务器出错了。例如,如果我的客户端告诉我文件名是“test.txt”,我的服务器会获取它,例如“test.txt´--------------------”或“test.txtPK”。我不明白为什么它不能正常获得名称。有谁知道为什么会发生这种情况?或者有更简单的方法来做到这一点吗?我的第二个问题是,我如何不仅在本地主机中而且在任何地方都可以使用它?我尝试将主机更改为我的 IP 地址,但没有成功。谢谢。

最佳答案

您永远不会在文件名之后发送行尾。因此,当服务器使用 readLine() 读取时,它将读取所有字符,直到找到可能位于文件内容中某处的行的第一个结尾。有时在“-----”之后,有时在“PK”之后。

关于java - 发送文件名,然后发送文件本身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10988541/

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