[英]Java: read from binary file, send bytes over socket
这应该很简单,但我现在无法理解它。 我想在套接字上发送一些字节,比如
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);
}
这工作,但现在我不想写Binte到Outputstream,但从二进制文件读取,然后写出来。 我知道(?)我需要一个FileInputStream来读取,我只是无法弄清楚构建整个事情的热点。
有人可以帮我吗?
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();
}
如果没有适当的异常处理,这将是天真的方法 - 在实际环境中,如果发生错误,您必须确保关闭流。
您可能想要查看Channel类以及stream的替代方法。 例如,FileChannel实例提供了可能更高效的transferTo(...)方法。
Socket s = new Socket("localhost", TCP_SERVER_PORT);
String fileName = "....";
使用fileName创建FileInputStream
FileInputStream fis = new FileInputStream(fileName);
创建一个FileInputStream文件对象
FileInputStream fis = new FileInputStream(new File(fileName));
从文件中读取
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(
s.getOutputStream()));
逐字节读取它
int element;
while((element = fis.read()) !=1)
{
dos.write(element);
}
或从缓冲区中读取
byte[] byteBuffer = new byte[1024]; // buffer
while(fis.read(byteBuffer)!= -1)
{
dos.write(byteBuffer);
}
dos.close();
fis.close();
从输入读取一个字节并将相同的字节写入输出
或者使用字节缓冲区,如下所示:
inputStream fis=new fileInputStream(file);
byte[] buff = new byte[1024];
int read;
while((read=fis.read(buff))>=0){
dos.write(buff,0,read);
}
请注意,您不需要使用DataStreams
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.