问题描述
这应该很容易,但我现在无法理解它。我想在套接字上发送一些字节,比如
This should be easy, but I can't get my head around it right now. I wanna send some bytes over a socket, like
Socket s = new Socket("localhost", TCP_SERVER_PORT);
DataInputStream is = new DataInputStream(new BufferedInputStream(s.getInputStream()));
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(s.getOutputStream()));
for (int j=0; j<40; j++) {
dos.writeByte(0);
}
这是有效的,但现在我不想将写入写入输出流,但是阅读从二进制文件,然后写出来。我知道(?)我需要一个FileInputStream来读取,我只是无法弄清楚构建整个事情的热点。
That works, but now I dont want to writeByte to the Outputstream, but read from a binary file, then write it out. I know(?) I need a FileInputStream to read from, I just can't figure out hot to construct the whole thing.
有人可以帮帮我吗?
推荐答案
public void transfer(final File f, final String host, final int port) throws IOException {
final Socket socket = new Socket(host, port);
final BufferedOutputStream outStream = new BufferedOutputStream(socket.getOutputStream());
final BufferedInputStream inStream = new BufferedInputStream(new FileInputStream(f));
final byte[] buffer = new byte[4096];
for (int read = inStream.read(buffer); read >= 0; read = inStream.read(buffer))
outStream.write(buffer, 0, read);
inStream.close();
outStream.close();
}
如果没有适当的异常处理,这将是天真的方法 - 在现实环境中你会如果发生错误,必须确保关闭流。
This would be the naive approach without proper exception handling - in a real-world setting you'd have to make sure to close the streams if an error occurs.
您可能想要查看Channel类以及流的替代方法。例如,FileChannel实例提供了传递效率更高的transferTo(...)方法。
You might want to check out the Channel classes as well as an alternative to streams. FileChannel instances, for example, provide the transferTo(...) method that may be a lot more efficient.
这篇关于Java:从二进制文件读取,通过套接字发送字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!