gpt4 book ai didi

java - SocketChannel 和 FileChannel.transferFrom/To

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

我刚刚了解了 java nio 包和 channel ,现在,我尝试使用 channel 编写一个非常简单的文件传输程序。我的目标是摆脱所有这些按字节阅读的东西。作为第一次尝试,我编写了以下服务器代码:

public class Server {
public static void main(String args[]) throws FileNotFoundException, IOException {
String destination = "D:\tmp\received";
int port = 9999;
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(9999));
SocketChannel socketChannel = serverSocketChannel.accept();
FileChannel fileChannel = new FileOutputStream(destination).getChannel();
fileChannel.transferFrom(socketChannel, 0, 32);
socketChannel.close();
serverSocketChannel.close();
}
}

和以下客户端代码:

public class Client {
public static void main(String args[]) throws FileNotFoundException, IOException {
String fileName = "D:\\dump\\file";
InetSocketAddress serverAddress = new InetSocketAddress("localhost", 9999);
FileChannel fileChannel = new FileInputStream(fileName).getChannel();
SocketChannel socketChannel = SocketChannel.open(serverAddress);
fileChannel.transferTo(0, fileChannel.size(), socketChannel);
socketChannel.close();
fileChannel.close();
}
}

通过预定义的端口传输预定义的 32 字节文件,无需任何类型的错误处理和内容。

这个程序编译和运行没有任何错误,但最后目标文件(“收到”)没有写入。

是否可以使用这种技术传输文件,还是我误解了什么?你能告诉我上面的代码我做错了什么吗?经过一些研究,我还没有找到任何解决方案,但只是找到了使用这种按字节的东西的代码片段(比如:while(有数据){读取 32 字节并将它们写入文件})。

最佳答案

"D:\tmp\received"

将这些反斜杠更改为正斜杠。这要么是一个非法文件名,它会引发您应该注意到的异常,要么至少它不是您认为您正在编写的文件名。

您还需要循环调用这些传输方法,直到它们传输完您期望的所有内容。这就是它们具有返回值的原因。检查 Javadoc。

关于java - SocketChannel 和 FileChannel.transferFrom/To,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33451051/

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