在Java中使用DataOutputStream发送文件 [英] sending a file using DataOutputStream in java
问题描述
我正在尝试构建一个将文件大小和内容发送到服务器的客户端。
I am trying to build a client that sends the file size and contents to server.
我正在尝试使用DataOutputStream。
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.
但是我不是确定如何实现这些,因为我对Java真的很陌生...
But I am not sure how to implement those because I am really new to java...
有人可以帮我吗?
谢谢!
推荐答案
这很简单,但是编写这些代码有点长,听起来很像作业。
It's quite simple, but the code is a bit long to write it all and sounds like homework.
我可以给你一些提示。
只需打开文件,使用
方法获取大小,以及 File
类的long length() writeLong(long)$ c
DataOutputStream
的$ c>方法将长度发送到服务器。然后一次读取一个文件块,然后使用 DataOutputStream
的 write(byte [])
方法发送
Just open the file, use the long length()
method of the class File
to get the size, and the writeLong(long)
method of DataOutputStream
to send the length to the server. Then just read the file a block at a time and use the write(byte[])
method of DataOutputStream
to send each block.
要一次读取一个文件块,只需创建一个 FileInputStream
并使用其 int read(byte [])
方法。注意不要假定此方法会填满整个缓冲区,因为不能保证这样做。阅读文档!
To read a file a block at a time, you will just create a FileInputStream
and use its int 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!
这篇关于在Java中使用DataOutputStream发送文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!