我刚刚了解了java nio包和通道,现在,我尝试用通道编写一个非常简单的文件传输程序。我的目标是摆脱所有这些旧的阅读材料。作为第一次尝试,我编写了以下服务器代码:
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(有数据){ read 32字节并将它们写入文件})。
发布于 2015-11-01 06:23:30
"D:\tmp\received"将这些反斜杠更改为正斜杠。这或者是一个非法的文件名,它会引发一个您应该注意到的异常,或者至少它不是一个与您认为正在编写的文件名相等的文件名。
您还需要在循环中调用这些传输方法,直到它们传输了您所期望的所有内容为止。这就是为什么他们有一个返回值。检查一下Javadoc。
https://stackoverflow.com/questions/33451051
复制相似问题