java中使用DataOutputStream发送文件
我正在尝试构建一个将文件大小和内容发送到服务器的客户端。
我正在尝试使用 DataOutputStream。
我假设我需要打开文件并获取文件大小并读取内容并发送它。
但我不知道如何实现这些,因为我对java真的很陌生......
任何人都可以帮助我吗?
谢谢你!
I am trying to build a client that sends the file size and contents to server.
I am trying to use DataOutputStream.
I am assuming that I need to open the file and and get size of file and read the contents and send it.
But I am not sure how to implement those because I am really new to java...
Can anyone help me about this?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
很简单,但是代码有点长,要全部写下来,听起来像是家庭作业。
我可以给你一些指示。
只需打开文件,使用类
File
的long length()
方法获取大小,使用writeLong(long)
方法DataOutputStream
将长度发送到服务器。然后一次读取文件一个块,并使用DataOutputStream
的write(byte[])
方法发送每个块。要一次读取一个文件块,您只需创建一个 FileInputStream 并使用其 int read(byte[]) 方法。请注意不要假设此方法会填满整个缓冲区,因为它不能保证这样做。阅读文档!
It's quite simple, but the code is a bit long to write it all and sounds like homework.
I can give you some indications.
Just open the file, use the
long length()
method of the classFile
to get the size, and thewriteLong(long)
method ofDataOutputStream
to send the length to the server. Then just read the file a block at a time and use thewrite(byte[])
method ofDataOutputStream
to send each block.To read a file a block at a time, you will just create a
FileInputStream
and use itsint read(byte[])
method. Be careful not to assume that this metod will fill up the whole buffer, because it is not guaranteed to do. Read the docs!